我想在单击按钮时更改画布上的文本标签。 如果要单击“上”按钮,我想将标签增加10;如果要单击“下”按钮,我要减少10。
这是我的代码,但是我不知道接下来要做什么:
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.consumtion = 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.consumtion))
'''button'''
self.but = tk.Button( text = "UP")
self.but.bind("<Button-1>", lambda event: self.consumption + 10)
self.but.place(relx=0.8, rely = 0.7, anchor = "center")
self.but = tk.Button(text = "DOWN")
self.but.bind("<Button-1>", lambda event: self.consumption - 10)
self.but.place(relx=0.9, rely = 0.7, anchor = "center")
# pack all
self.canvas.pack()
sys=Sys()
答案 0 :(得分:3)
您可以使用记录在案的画布itemconfigure
方法来更改画布上任何对象的任何配置选项。
例如,您可以编写一个名为change_consumption
的方法,该方法采用一个参数来更改值的大小,并且可以使用itemconfigure
来更改画布上显示的内容:
def change_consumption(self, amount):
self.consumption += amount
self.canvas.itemconfigure(self.cons, text=self.consumption)
您将为“向上”按钮绑定到此功能;对于“下”,您将通过-10
:
self.but.bind("<Button-1>", lambda event: self.change_consumption(10))
答案 1 :(得分:0)
在调用变量self.consumtion
时会出现拼写错误,但是当您尝试更改它时,变量self.consumption
会出现拼写错误。
画布上的文本对象不能像普通标签那样工作,而可以像文本小部件那样工作,可以跟踪选择以及选择,删除和插入的方法。我创建了一个更改文本的函数,然后让按钮以所需的偏移量调用该函数:
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()