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\
You can use the documented itemconfigure
method of the canvas to change any configuration option of any object on the canvas.
For example, you could write a method named change_consumption
that takes a parameter for how much to change the value by, and it can use itemconfigure
to change what appears on the canvas:
def change_consumption(self, amount):
self.consumption += amount
self.canvas.itemconfigure(self.cons, text=self.consumption)
You would bind to this function like this for the "up" button; for "down" you would pass -10
:
self.but.bind("<Button-1>", lambda event: self.change_consumption(10))
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("<Button-1>", 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("<Button-1>", 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