简体   繁体   English

更改Tkinter标签

[英]python - change tkinter label

The following script creates a tkinter window with a text label, exit button and change-text button: 以下脚本创建一个带有文本标签,退出按钮和更改文本按钮的tkinter窗口:

from tkinter import *
from tkinter import ttk

class Window(Frame):

    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.master = master
        self.init_window()

    def init_window(self):
        test_label = Label(root, text="none").grid(row=0, column=0, sticky=W)

        change_text_btn = Button(root, text="change_text", command=self.set_label_text).grid(row=2, column=0, sticky=W)
        exit_btn = Button(root, text="Exit", command=self.client_exit).grid(row=2, column=1, sticky=W)

    def set_label_text(self):
        test_label.config(text='changed the value')

    def client_exit(self):
        exit()

if __name__ == '__main__':
    root = Tk()
    app = Window(root)
    root.mainloop()

After click on change_text_btn I get a NameError: name 'test_label' is not defined error. 单击change_text_btn后,我得到一个NameError: name 'test_label' is not defined错误。 So the problem is that test_label created in init_window() is not avaliable from set_label_text() beacuse of the scope. 所以问题是, test_label中创建init_window()是不是从avaliable set_label_text()怎么一回事,因为范围。 How do I fix it? 我如何解决它?

To overcome the issue, you can make test_label an instance variable by prefixing it with self . 为了解决这个问题,您可以在test_label实例变量前加上self前缀,以使其成为实例变量。 Besides that, when you chain methods like that, what happens is you assign None to your variable, since grid() returns None - instead, place each method in a separate line (this stands for all of your buttons): 除此之外,当您像这样链接方法时,发生的事情是您将None分配给变量,因为grid()返回None而是将每个方法放在单独的行中(这代表所有按钮):

self.test_label = Label(root, text="none")
self.test_label.grid(row=0, column=0, sticky=W)

Of course, you'd need to refer to it with self.test_label later on in your set_label_text function. 当然,稍后需要在set_label_text函数中使用self.test_label进行引用。

Other than that, I suggest you get rid of from tkinter import * , since you don't know what names that imports. 除此之外,我建议您摆脱from tkinter import * ,因为您不知道该导入的名称。 It can replace names you imported earlier, and it makes it very difficult to see where names in your program are supposed to come from. 它可以替换您先前导入的名称,并且很难查看程序中的名称。 Use import tkinter as tk instead. 使用import tkinter as tk代替。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM