繁体   English   中英

如何更新 python gui?

[英]How to update python gui?

我想每秒更新我的 gui(我实际上并不关心时间,但它应该像实时一样)。 我有一个脚本,实际上 Label 作为 int 应该增加一并显示。 但我没有得到改变,我也想根据根的宽度放置 Label,但它没有更新。 只有更新是一个问题,也许有人可以帮助我。 (我是初学者 - 菜鸟)。

脚本:


from tkinter import *
import time

c = 0
root = Tk()
root.title("Real Time Plot")
root.minsize(width = 200, height = 300)
m = root.winfo_reqwidth() / 2

root.update()
Text = Label(root, text = c)
Text.place(x =m, y = 150)
c = c + 1
print(m)

root.mainloop()

我创建了一个计时器,所以我想你可以像我一样做。 希望这对你有用。

首先,创建一个 StringVar:

文本 = StringVar(值 = “文本”)

然后用文本变量创建一个 Label。 你的标签 = 标签(根,文本变量 = 文本)

然后只需制作一个 function 将更新 yourlabel:yourlabel.set(在这里传递新值)

因此,您的 yourlabel 将具有您传递的值。 因此,您可以使用 self.after 之类的东西每 1000 毫秒更新一次函数。

您只更新变量值,而不是 label 的值。 您需要在增加 c 的内容后更新 label:

Text.configure(text=c)

所以它变成了这样:

from tkinter import *
import time

c = 0
root = Tk()
root.title("Real Time Plot")
root.minsize(width = 200, height = 300)
m = root.winfo_reqwidth() / 2

root.update()
Text = Label(root, text = c)
Text.place(x =m, y = 150)
root.update()

time.sleep(2)
c = c + 1
Text.configure(text=c)
root.update()

print(m)

root.mainloop()

我对您的代码做了一些小的更新,例如添加睡眠时间,以更好地显示行为。

您必须使用 Python 线程,它将完美地执行此操作!

这是代码:

from tkinter import *
import threading
import time

def realtime_update():
    while True:
        global c, Text
        c += 1
        Text.configure(text=c+1)
        time.sleep(0.001)
        root_width = root.winfo_geometry()
        root_width = root_width.split('x')
        root_width = int(root_width[0])

        Text.place(x=root_width/2, y=150)
        time.sleep(0.01)

c = 0
root = Tk()
root.title("Real Time Plot")
root.minsize(width = 200, height = 300)
m = root.winfo_reqwidth() / 2

Text = Label(root, text = c)
Text.place(x=int(m), y = 150)
print(m)
threading.Thread(target=realtime_update, daemon=True).start()
root.mainloop()

它解决了以下问题:

  1. 实时更新(精度到 0.01s)
  2. Label 在根 window 调整大小时更改 position

暂无
暂无

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

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