gpt4 book ai didi

python - 在线程中调用 pack_forget()

转载 作者:太空宇宙 更新时间:2023-11-04 10:02:21 25 4
gpt4 key购买 nike

我有一个看起来像这样的 Python 程序

from tkinter import *
import threading, time
def cancel ():
print ("Stop!")
def thread ():
threading.Thread (target = new).start ()
def new ():
b.pack_forget ()
c = Canvas (root, width = 200, height = 25, bg = "white")
c.pack ()
Button (root, text = "OK", command = root.destroy).pack ()
try:
for x in range (200):
time.sleep (0.02)
c.create_rectangle ((x, 2, x + 1, 26), outline = "green", fill = "green")
root.destroy ()
except: pass
root = Tk ()
root.title ("Threading")
b = Button (root, text = "Begin.", command = thread)
b.pack ()
root.mainloop ()

但是,每次调用 pack_forget () 时它都会崩溃。我知道我可以这样做:

from tkinter import *
import threading, time
def cancel ():
print ("Stop!")
def thread ():
b.pack_forget ()
threading.Thread (target = new).start ()
def new ():
c = Canvas (root, width = 200, height = 25, bg = "white")
c.pack ()
Button (root, text = "OK", command = root.destroy).pack ()
try:
for x in range (200):
time.sleep (0.02)
c.create_rectangle ((x, 2, x + 1, 26), outline = "green", fill = "green")
root.destroy ()
except: pass
root = Tk ()
root.title ("Threading")
b = Button (root, text = "Begin.", command = thread)
b.pack ()
root.mainloop ()

但是,对于其他程序,是否可以在线程中调用 pack_forget。谢谢。

最佳答案

您不能从创建 GUI 的线程以外的线程调用 tkinter 函数。您需要设置一个线程安全的队列,并从工作线程向队列放置一些东西。主线程可以轮询这个队列并响应数据。

例如,您可以将像"pack_forget" 这样简单的内容放入队列中,当主程序从队列中取出字符串"pack_forget" 时,它知道调用该函数。

关于python - 在线程中调用 pack_forget(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42877869/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com