我在主线程上运行了 tkinter GUI,在第二个线程上运行了一个 while 循环,它更新标签内容以在 GUI 上显示 n 秒的持续时间。这本身运行良好。 现在我想在 GUI 上使用一个 << 和 >> 按钮来循环:
- 暂停当前迭代,用上一个项目调用显示方法,完成后恢复迭代
- 中途跳过当前项目并移至下一个项目。 但是我找不到如何生成循环中断事件。我无法根据按钮生成的某些变量/数据库条目(如此处 Python: Tkinter pausing a while loop )调用继续或 sleep ,因为中断可能发生在循环中的任何位置(而不是在特定的 if/else 行)
我已经引用了 codemy.com 的查看器程序 - https://github.com/flatplanet/Intro-To-TKinter-Youtube-Course/blob/master/viewer.py当然还有谷歌。
这是我正在尝试做的事情的片段。 ( https://gitlab.com/ananya26nov/PixelescoPy )
主线程运行GUI
guiObj = GuiWindow()
thread_list = []
thread = threading.Thread(target=worker, args=(guiObj,))
thread_list.append(thread)
thread.start()
guiObj.run_window_on_loop()
thread.join()
guiObj.quit_window()
线程的worker方法是这样的:
while len(files_not_viewed) != 0:
chosen = random.choice(files_not_viewed)
if is_not_viewed(chosen):
pictureObj = Picture(chosen)
# Display the chosen for <timer> seconds
pictureObj.display(guiObj)
time.sleep(timer)
# Change the status of "chosen" to "viewed"
mark_as_viewed(chosen)
files_not_viewed = list(set(files_not_viewed) - set([chosen]))
显示方法调用下面类的'add_input_section'方法
class GuiWindow():
def __init__(self):
self.root = Tk()
self.screen_width = self.root.winfo_screenwidth()
self.screen_height = self.root.winfo_screenheight()
self.image_label = None
self.image = None
self.folder_path = None
self.timer = None
def run_window_on_loop(self):
button_exit = Button(self.root, text="Exit Program", command=self.root.quit)
button_exit.grid(row=1, column=1)
self.root.mainloop()
def quit_window(self):
self.root.quit()
def resize(self, image_path):
my_pic = Image.open(image_path)
pic_height = my_pic.height
pic_width = my_pic.width
if my_pic.height > (self.screen_height - 100):
new_height= self.screen_height - 100
new_width = int(new_height / pic_height * pic_width)
pic_height = new_height
pic_width = new_width
if pic_width > self.screen_width - 5:
new_width = self.screen_height - 5
new_height = int(new_width / pic_width * pic_height)
pic_height = new_height
pic_width = new_width
resized_image = my_pic.resize((pic_width, pic_height), Image.ANTIALIAS)
return resized_image
def add_image(self, image_path):
resized_img = self.resize(image_path)
image_obj = ImageTk.PhotoImage(resized_img)
image_label = Label(self.root, image=image_obj,
height=resized_img.height,
width=resized_img.width)
self.image = image_obj # DO NOT REMOVE - Garbage collector error
if self.image_label is not None:
self.remove_image()
image_label.grid(row=0, column=0, columnspan=3)
self.image_label = image_label
def remove_image(self):
self.image_label.grid_forget()
最佳答案
使用 tk.BooleanVar() 来操作变量,并在您尝试暂停时跟踪状态,以便您可以在完成后继续。
关于python - 如何将 tkinter 事件用于 'continue' 或暂停不同的 while 循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62702079/