不能 运行 使用 Tkinter 的无限线程
Can't run an infinite thread with Tkinter
下面的代码有效,但如果我使线程成为一个无限循环(通过取消注释行 i=False),window 将不再显示。我错过了什么?
我的目标是在显示图像时不断更新图像。
from PIL import Image,ImageTk
from tkinter import Tk,Canvas,NW,mainloop
import threading
from time import sleep
from random import randint
imgx = 512; imgy = 512
def mi_thread():
global pix
i=True
while i:
#i=False
for k in range(imgy):
pix[k,k]=(randint(0,255),randint(0,255),randint(0,255))
sleep(1)
window = Tk()
canvas = Canvas(window, width = imgx, height = imgy, bg = "#000000");canvas.pack()
img2 = Image.new("RGB", (imgx, imgy))
pix = img2.load()
t= threading.Thread(target=mi_thread())
t.start()
imgx =ImageTk.PhotoImage(img2)
canvas.create_image((0, 0), image = imgx, state = "normal", anchor = NW)
mainloop()
在threading.Thread(target=mi_thread())
中你实际上是运行你的函数。您需要删除括号并仅传递函数引用。即:
threading.Thread(target = mi_thread)
下面的代码有效,但如果我使线程成为一个无限循环(通过取消注释行 i=False),window 将不再显示。我错过了什么?
我的目标是在显示图像时不断更新图像。
from PIL import Image,ImageTk
from tkinter import Tk,Canvas,NW,mainloop
import threading
from time import sleep
from random import randint
imgx = 512; imgy = 512
def mi_thread():
global pix
i=True
while i:
#i=False
for k in range(imgy):
pix[k,k]=(randint(0,255),randint(0,255),randint(0,255))
sleep(1)
window = Tk()
canvas = Canvas(window, width = imgx, height = imgy, bg = "#000000");canvas.pack()
img2 = Image.new("RGB", (imgx, imgy))
pix = img2.load()
t= threading.Thread(target=mi_thread())
t.start()
imgx =ImageTk.PhotoImage(img2)
canvas.create_image((0, 0), image = imgx, state = "normal", anchor = NW)
mainloop()
在threading.Thread(target=mi_thread())
中你实际上是运行你的函数。您需要删除括号并仅传递函数引用。即:
threading.Thread(target = mi_thread)