简体   繁体   English

为什么Python tkinter标签小部件不更新?

[英]Why does Python tkinter label widget not update?

class First_Frame(Frame):
    def __init__(self,master):
        super().__init__(master)
        self.grid()
        self.widgets()

    def widgets(self):
        self.commandent1=StringVar()
        self.commandent1.set("tutaj bedzie sie pokazywal aktualny status")
        self.img=Image.open("database.XPM","r")
        self.image_true=ImageTk.PhotoImage(self.img)
        self.label=Label(self,image=self.image_true).grid()
        self.label2=Label(self,text="twoje gui uzytkownika").grid()
        self.widgets_2()

    def widgets_2(self):
        self.status_text=Label(self,text=self.commandent1.get())
        self.entry1=Entry(self)
        self.entry1.bind("<Return>",self.update_status)
        self.entry1.grid()
        self.status_text.grid()
    def update_status(self):
        self.x=self.entry1.get()
        self.commandent1.set(self.x)

You have 2 main reasons your Label (not text) widget is not updating. 您的标签 (非文本)小部件没有更新的主要原因有两个。

Reason 1. You need to handle the event that is being passed to update_status from the binding. 原因1.您需要处理从绑定传递到update_status的事件。 To do this just add event or any argument name really you want. 为此,只需添加event或您真正想要的任何参数名称。 I just use event for readability. 我只是使用event来提高可读性。

def update_status(self, event):

Reason 2. You need to and the less obvious reason here for some is the way you are using your StringVar() on the label widget. 原因2。您需要(这里不明显的原因StringVar()是在标签小部件上使用StringVar()的方式。 Here you are assigning the current text value of the StringVar() only once and never again. 在这里,您只分配一次StringVar()的当前文本值, StringVar()一次。 To properly use the StringVar() with a label widget you will need to assign the StringVar() to a textvariable argument and not a text argument. 为了将StringVar()与标签窗口小部件一起正确使用,您需要将StringVar()分配给textvariable参数而不是text参数。

Like this: 像这样:

Label(self,textvariable=self.commandent1).grid()

Note I took out the image portion of your code as it was irrelevant to the question. 注意,我删除了代码的图像部分,因为它与问题无关。 Your final code should look something like this: 您的最终代码应如下所示:

from tkinter import *

class First_Frame(Frame):
    def __init__(self, master):
        super().__init__()
        self.grid()
        self.widgets()

    def widgets(self):
        self.commandent1 = StringVar()
        self.commandent1.set("tutaj bedzie sie pokazywal aktualny status")
        Label(self,text="twoje gui uzytkownika").grid()
        self.widgets_2()

    def widgets_2(self):
        self.entry1 = Entry(self)
        self.entry1.bind("<Return>", self.update_status)
        self.entry1.grid()
        Label(self,textvariable=self.commandent1).grid()

    def update_status(self, event):
        self.commandent1.set(self.entry1.get())


root = Tk()
First_Frame(root)
root.mainloop()

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

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