蟒蛇的Tkinter通过标签按钮命令改变文本值(python Tkinter label chang

2019-10-18 19:14发布

我使用Tkinter的标签控件来显示一些文本到我的UI框架和我想的标签改变文本的每次我点击按钮。 在我来说,我得到了错误的...它并没有改变,这可能吗?

这是我的代码..

currentCounterNumber = "0"

def counterPlus(teller_num):
    #.... the data is working well ....
    data = s.recv(1024) 
    if data:
        currentCounterNumber = data
......
class Content(tk.Frame):
def __init__(self, master, teller_name,*args, **kwargs):
    tk.Frame.__init__(self, *args, borderwidth=20, **kwargs)
    self.L4 = tk.Label(self, text="Serving # " + currentCounterNumber +"!")
    self.L4.pack( side = "top", fill="both", expand=False)      

    self.button1 = tk.Button(self, text="+", width=15, command=lambda: counterPlus(teller_no))
    self.button1.pack(side = "top", fill="both", expand=True)

Answer 1:

假设content_obj = Content(....)被定义。

您可以通过更改文本:

content_obj.L4['text'] = "Serving # {}!".format(currentCounterNumber)

要么

content_obj.L4.configure(text="Serving # {}!".format(currentCounterNumber))
#       OR     config

例:

from Tkinter import * # Python 3.x: from tkinter import *

def advance():
    lb['text'] = str(int(lb['text']) + 1)
    root.after(1000, advance)

root = Tk()
lb = Label(root, text='0')
lb.pack()
root.after(1000, advance)
root.mainloop()


文章来源: python Tkinter label changing text value by Button Command