我一直在四处寻找这个问题,但所有的解决方案都感觉非常复杂,即使这样,我也无法让它按照我想要的方式工作。我正在制作一个程序,从一个文件夹中随机打开一个图像,等待10秒,然后从同一个文件夹中打开另一个随机图像,并继续运行
很简单,我能够在一个While-True循环中完成它,并随着时间的推移完成“等待10秒”部分。sleep(10)。但是,我想有一个按钮,只要我想它重置它。我在tkinter
中执行此操作,我有一个启动它的按钮,但当我添加一个按钮重置它时,我无法单击它,当我尝试时,程序崩溃。这是因为它是在时间。睡眠(10)和整个程序停止10秒。对于任何对代码感兴趣的人,请看这里
from tkinter import *
import random
import os
from PIL import Image
import time
root = Tk()
def AnmuViewer():
while True:
random_pic = (random.choice(os.listdir("D:/de_clutter/memez/anmu")))
openPic = Image.open('D:/de_clutter/memez/anmu/' + random_pic)
openPic.show()
time.sleep(10)
continue
def Restart():
AnmuViewer()
start_btn = Button(root, text = "Start", command = AnmuViewer)
start_btn.pack()
next_btn = Button(root, text = 'Restart', command = Restart)
next_btn.pack()
root.mainloop()
我知道我不需要一个“重启”按钮,因为再次点击“启动”按钮也会做同样的事情。不管怎样,“开始”按钮本身也是不可点击的
我已经研究过线程,所以我想做一个从10开始倒计时的函数,当它达到10时,AnmuViewer()
会重新开始,这样我就可以在任何时候再次单击“开始”并从头重置整个代码。但我也没能做到。有什么建议吗
将
while
与tkinter一起使用将导致mainloop()
出现一些问题,并将冻结该问题。您应该使用不会冻结GUI的after(ms,func)
。一个非常简单的代码可以做到这一点,请看这里:我已经用注释解释了代码,以便在移动中更容易理解。我没有假设图像的路径,所以我正在动态地选择路径,如您所见。代码看起来很长,因为为了更好地理解,我简化了大多数代码行
无论如何,您需要调整图像大小,使其适合每个人的屏幕,因为像素和屏幕分辨率因设备而异。看一看here
您可以在同一个按钮中组合
start
和reset
,但也可以添加一个调用相同函数的重置按钮(注释代码)。 也就是说,启动时,系统将重置为其初始状态,此处callback
值设置为None
大多数时候,使用
tkinter.mainloop
比使用自定义while
循环更好。在GUI中使用time.sleep
通常会导致灾难,因为它会在执行过程中阻止所有交互我用一个
text label
替换了这些图像。为了简单起见,您必须更改它相关问题 更多 >
编程相关推荐