我有一个看起来像这样的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。感谢。
答案 0 :(得分:4)
您不能从创建GUI的线程以外的线程调用tkinter函数。您需要设置一个线程安全的队列,并从工作线程中放置一些东西。主线程可以轮询此队列并响应数据。
例如,您可以在队列中放置一些像"pack_forget"
这样简单的东西,当主程序从队列中拉出字符串"pack_forget"
时,它就会知道调用该函数。