Python 3,从不同的功能更新Tkinter中的标签?

时间:2018-04-18 23:46:01

标签: python python-3.x user-interface tkinter label

所以我试图在Tkinter中创建一个GUI并更新之前在main函数中创建的标签,并使用单击按钮来触发更改。然而,无论我尝试什么,包括在同一个网格点上放置一个新标签似乎都有效。

我该怎么做?

from tkinter import *

class MyFirstGUI:
    def __init__(self, master):
        self.master = master
        master.title("Login")
        Label(master, text="E-Mail Address:").grid(row=0)
        Label(master, text="Password:").grid(row=1)
        Label(master, text="UserID:").grid(row=2)
        e1 = Entry(master)
        e2 = Entry(master)
        e3 = Entry(master)
        e1.grid(row=0, column=1)
        e2.grid(row=1, column=1)
        e3.grid(row=2, column=1)
        b1 = Button(text ="Login!", command=self.test)
        b1.grid(row=3, column=1)
        Label(master, text="Status: ").grid(row=4, column=0)
        Label(master, text="Boop!").grid(row=5, column=0)   

    def test(self):
        # I want to change the label named Boop in this function when button is pressed.
        # Target word is "Beep!"

root = Tk()
my_gui = MyFirstGUI(root)
root.mainloop()

1 个答案:

答案 0 :(得分:2)

要更改任何内容,您必须保存对象。在课堂上,你需要给它起一个以" self开头的名字。"。

from tkinter import *

class MyFirstGUI:
    def __init__(self, master):
        self.master = master
        master.title("Login")
        Label(master, text="E-Mail Address:").grid(row=0)
        Label(master, text="Password:").grid(row=1)
        Label(master, text="UserID:").grid(row=2)
        e1 = Entry(master)
        e2 = Entry(master)
        e3 = Entry(master)
        e1.grid(row=0, column=1)
        e2.grid(row=1, column=1)
        e3.grid(row=2, column=1)
        b1 = Button(text ="Login!", command=self.test)
        b1.grid(row=3, column=1)
        Label(master, text="Status: ").grid(row=4, column=0)
        self.mylbl = Label(master, text="Boop!")
        self.mylbl.grid(row=5, column=0)

    def test(self):
        self.mylbl.config(text="Beep!")

root = Tk()
my_gui = MyFirstGUI(root)
root.mainloop()

请注意,我初始化了2行而不是1行。如果您想稍后访问该对象,这一点非常重要。