【问题标题】:why my label is not self updating?为什么我的标签不能自我更新?
【发布时间】:2017-05-18 16:34:24
【问题描述】:

我已经阅读了许多关于 update_idletasks() 的帖子。我以为我理解了,我将其添加到代码中。标签应该显示 # 3 因为我只有 3 行记录,但它没有。

我确实使用了一个按钮,并且标签有效,但 update_idletask() 没有。

有没有办法不使用按钮通过 update_idletasks() 使这个标签自我更新?

我认为它不起作用是因为它没有进入循环? 请指导我。

import sqlite3
import tkinter as t
import time

class SampleApp(t.Tk):

    def __init__(self,parent):
        t.Tk.__init__(self,parent)
        self.parent=parent
        self.initialize()

    def initialize(self):
        self.grid()
#GUI-------------------------------------
        self.labelVariable=t.StringVar()
        self.label=t.Label(self, textvariable=self.labelVariable, bg="yellow", width=50, height=20)
        self.label.pack(fill=t.X, expand=1)


        #self.button=t.Button(self, text="get status", pady=5, command=self.status)
        #self.button.pack(anchor=t.S, fill=t.X, expand=1)


#formula______________________________________

    def status(self):
        conn=sqlite3.connect("employees.db")
        cursor=conn.cursor()
        cursor.execute("SELECT COUNT(*) FROM Company")
        self.labelVariable.set(cursor.fetchone()[0])

        self.update_idletasks()
        self.after(0,self.status)


app = SampleApp(None)
app.mainloop()

【问题讨论】:

    标签: python tkinter label


    【解决方案1】:

    您只需要致电self.status()....而self.update_idletasks() 不是必需的。如果你要打开一个连接,你也必须关闭它。

    把你的班级改成这样:

    class SampleApp(t.Tk):
    
        def __init__(self,parent):
            t.Tk.__init__(self,parent)
            self.parent=parent
            self.initialize()
    
    
        def initialize(self):
            self.grid()
    
            self.labelVariable=t.StringVar()
            self.label=t.Label(self, textvariable=self.labelVariable, bg="yellow", width=50, height=20)
            self.label.pack(fill=t.X, expand=1)
            self.status()
    
        def status(self):
            conn=sqlite3.connect("employees.db")
            cursor=conn.cursor()
            cursor.execute("SELECT COUNT(*) FROM Company")
            self.labelVariable.set(cursor.fetchone()[0])
            conn.close()
            self.after(10,self.status)
    

    注意:对于delay 参数(单位为毫秒),您不应将.after 与0 或几乎任何低于10 的值一起使用。

    【讨论】:

    • 我强烈反对self.after(0, ...)。您应该使用更大的数字。使用零意味着“之后”队列永远不会清空,这会阻止处理正常事件。即使是1(一)的值也比零好,尽管像10100 这样更大的数字会更好。
    • 你是 100% 正确的,我只是使用了 OP 示例中的那个
    • 感谢 Bryan 和 abccd 的快速回复。我很感激。我更新了代码,但仍然没有看到标签上的数字。 “3”,记录行。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-01
    • 1970-01-01
    • 2023-02-22
    相关资源
    最近更新 更多