Python 按下按钮时更新Tkinter中的标签
我想做一个“程序”,当你按下一个按钮并打印出一个变量时,它会更新一个标签,但是用我的代码,它不起作用。有人能帮我吗 提前谢谢Python 按下按钮时更新Tkinter中的标签,python,tkinter,Python,Tkinter,我想做一个“程序”,当你按下一个按钮并打印出一个变量时,它会更新一个标签,但是用我的代码,它不起作用。有人能帮我吗 提前谢谢 from Tkinter import * root = Tk() x = 0 def test(): global x x += 1 label_1.update() label_1 = Label(root, text=x) button_1 = Button(root, text='Click', command=test) butt
from Tkinter import *
root = Tk()
x = 0
def test():
global x
x += 1
label_1.update()
label_1 = Label(root, text=x)
button_1 = Button(root, text='Click', command=test)
button_1.grid(row=0, column=0)
label_1.grid(row=0, column=1)
root.mainloop()
用
label\u 1.config(text=x)代替label\u 1.update()
(which),用label\u 1.config(text=x)代替label\u 1.update()
(which),另一种解决方案是:使用textvariable
标记和Tkinter IntVar
例如:
from Tkinter import *
root = Tk()
x = IntVar()
def test():
global x
x.set(x.get() + 1)
label_1 = Label(root, text=x.get(), textvariable = x)
button_1 = Button(root, text='Click', command=test)
button_1.grid(row=0, column=0)
label_1.grid(row=0, column=1)
root.mainloop()
*编辑:删除了标签\u 1.update()
调用,因为它是不必要的另一种解决方案:使用textvariable
标记和Tkinter IntVar
例如:
from Tkinter import *
root = Tk()
x = IntVar()
def test():
global x
x.set(x.get() + 1)
label_1 = Label(root, text=x.get(), textvariable = x)
button_1 = Button(root, text='Click', command=test)
button_1.grid(row=0, column=0)
label_1.grid(row=0, column=1)
root.mainloop()
*编辑:删除了标签\u 1.update()
调用,因为如果您想将其作为一个类编写,它是不必要的,这有许多优点
import Tkinter as tk
class Application(tk.Frame):
def __init__(self, master=None):
self.x = tk.IntVar()
tk.Frame.__init__(self, master)
self.pack()
self.createWidgets()
def createWidgets(self):
tk.Label(self, textvariable=self.x).pack()
tk.Button(self, text='Click', command=self.increment).pack()
def increment(self):
self.x.set(self.x.get() + 1)
root = tk.Tk()
app = Application(master=root)
app.mainloop()
如果你想把它写成一个类,它有很多优点
import Tkinter as tk
class Application(tk.Frame):
def __init__(self, master=None):
self.x = tk.IntVar()
tk.Frame.__init__(self, master)
self.pack()
self.createWidgets()
def createWidgets(self):
tk.Label(self, textvariable=self.x).pack()
tk.Button(self, text='Click', command=self.increment).pack()
def increment(self):
self.x.set(self.x.get() + 1)
root = tk.Tk()
app = Application(master=root)
app.mainloop()