简体   繁体   English

使用Tkinter标签更改文本的Python参考

[英]Python reference with Tkinter label change text

I am trying to to change my Tkinter Label text from another function. 我试图从另一个函数更改我的Tkinter Label文本。 Somehow I cannot reference the Label and therefore not changing the Label, only add a new on top of the old. 不知何故,我无法引用Label ,因此不会更改Label,只在旧版本上添加一个新的。

self.errorLabel['text'] = 'second' works inside the init-function of Window, but I need to be able to do it from another function, therefore a reference fault somehow. self.errorLabel['text'] = 'second'在Window的init函数内部工作,但我需要能够从另一个函数执行它,因此以某种方式引用错误。

This is my code: 这是我的代码:

import sys
from tkinter import *
from tkinter import ttk

class Window(Frame):

    def __init__(self, master = None):
        Frame.__init__(self, master)
        self.master = master
        self.errorLabel = Label(self, text="some text").grid(row=0)
        self.init_window()

    def init_window(self):
        self.master.title("Example")
        self.pack(fill=BOTH, expand=1)

        goButton = Button(self, text="Go!", command=self.client_go).grid(row=1, column=1)
        quitButton = Button(self, text="Close", command=self.client_exit).grid(row=1, column=0)

    def client_exit(self):
        exit()

    def client_go(self):
        self.errorLabel['text'] = 'second' # TypeError: 'NoneType' object does not support item assignment
        self.errorLabel = Label(self, text="second").grid(row=0)
        return

root = Tk()
root.geometry("800x500")
app = Window(root)
root.mainloop()

This is a very common error with tkinter code. 这是tkinter代码的一个非常常见的错误。 Widget.grid returns None , so when you write: Widget.grid返回None ,所以当你写:

self.errorLabel = Label(self, text="some text").grid(row=0)

self.errorLabel is None . self.errorLabelNone Instead, create the widget and use it's geometry manager in separate lines of code: 相反,创建窗口小部件并在单独的代码行中使用它的几何管理器:

self.errorLabel = Label(self, text="some text")
self.errorLabel.grid(row=0)

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

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