Python通过线程tkin进行通信

2024-07-07 08:34:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在创建一个基于文本的游戏,并希望有多少秒,它已经运行计数器,这是我第一次使用tkinter,所以我不完全确定我做的都是正确的。当我尝试用counter()函数更新upt_label['text']upt_table时,遇到了以下问题。你知道吗

对于python3.3,我需要引用什么才能在counter()中更改该变量?你知道吗

from tkinter import *
import time
from threading import Thread

global upt_label

class OutBox(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent, background="black")

        self.parent = parent

        self.initUI()

    def initUI(self):
        self.parent.title("Text Adventure!")
        self.pack(fill=BOTH, expand=1)
        tpp_label = Label(self, text="Text Adventure!", fg="white", background="black", anchor="center", font=("Arial", 18))
        tpp_label.pack()
        upt_label = Label(self, text = "Uptime: 0", fg="white", background="black", anchor="center", font=("Arial", 12))
        upt_label.pack()

def main():
    root = Tk()
    root.geometry("560x720")
    app = OutBox(root)
    root.mainloop()

def counter():
    uptime = 0
    while True:
        upt_label['text'] = 'Uptime: %s' % uptime
        time.sleep(1)
        uptime = uptime + 1

gui_thread = Thread(target = main, args = ())
gui_thread.start()

upt_thread = Thread(target = counter, args = ())
upt_thread.start()

Tags: textimportselfdefcounterrootthreadlabel
1条回答
网友
1楼 · 发布于 2024-07-07 08:34:40

部分问题是无法保证gui线程会在计数器线程运行之前初始化。使问题更加复杂的是,除了创建tkinter小部件的线程外,您无法从任何线程安全地访问tkinter小部件。所以,即使你解决了启动顺序问题,你仍然有这个问题要解决。你知道吗

好消息是,这个问题不需要线程。事实上,线程使这个问题变得更加困难。你知道吗

如果你想每秒钟运行一次,用after来调用一个函数,然后让这个函数用after来安排自己在一秒钟内再次运行。你知道吗

下面是一个粗略的例子:

   def counter():
        global uptime
        uptime += 1
        upt_label['text'] = 'Uptime: %s' % uptime
        root.after(1000, counter)

注意这个函数将如何更新标签,然后安排在一秒钟后再次调用它自己。这可能有点不准确,因为它不能保证在一秒钟后准确地运行。一个更准确的解决方案是节省程序启动的时间,然后得到当前时间并做一些计算。这将使您在长时间运行的程序过程中获得更准确的表示。你知道吗

相关问题 更多 >