tkinter changeable value on canvas

后端 未结 2 878
轮回少年
轮回少年 2021-01-27 09:16

I want to change the text label on a canvas when buttons are clicked. I want to increase the label by 10 if the button \"up\" is clicked and decrease by 10 if the button \"down\

2条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-27 09:31

    There is a spelling error where you call a variable self.consumtion but when you try to change it its called self.consumption.

    Text objects on canvas does not work like normal labels but more like text widgets, keeping track of selections and with methods for selection, deletion and insert. I created a function to change the text and then let the buttons call that function with the desired offset:

    import tkinter as tk
    
    class Sys(tk.Tk, object):
        def __init__(self):
            super(Sys, self).__init__()
            self.title('SYSTEM')
            self.geometry('{0}x{1}'.format(500, 500))   # dimentions
            self.consumption = 300
            self._build_system() 
    
        def _build_system(self):
            self.canvas = tk.Canvas(self, bg='lightgreen',  height=500, width=500)   # dimentions
            '''changeable value'''
            self.cons = self.canvas.create_text(250,250, text = str(self.consumption))
    
            '''button'''
            self.but = tk.Button( text = "UP")
            # Call on function change_label with amount = 10
            self.but.bind("", lambda event: self.change_label(10))
            self.but.place(relx=0.8, rely = 0.7, anchor = "center")
            self.but = tk.Button(text = "DOWN")
            # Call on function change_label with amount = -10
            self.but.bind("", lambda event: self.change_label(-10))
            self.but.place(relx=0.9, rely = 0.7, anchor = "center")
    
           # pack all
            self.canvas.pack()
    
        def change_label(self, amount):
            # Adjust self.consumption with amount
            self.consumption += amount
            # Delete all chars in self.cons
            self.canvas.dchars(self.cons, 0, tk.END)
            # Insetr new text in self.cons
            self.canvas.insert(self.cons, 0, str(self.consumption)) 
    
    sys = Sys()
    

    Have a look at Editing Canvas Text Items

提交回复
热议问题