如何使用tkinter事件“继续”或暂停不同的while循环?

2024-03-29 13:02:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我在主线程上运行tkinter GUI,在第二个线程上运行while循环,该循环在n秒的时间内更新要在GUI上显示的标签内容。它本身运行良好。 现在我想要一个<&书信电报;及>&燃气轮机;GUI上创建循环的按钮:

  • 暂停当前迭代,使用上一项调用display方法,完成后继续迭代
  • 中途跳过当前项目,转到下一个项目。 但我找不到如何生成循环中断事件。我无法根据按钮生成的某些变量/db条目调用continue或sleep(如此处Python: Tkinter pausing a while loop),因为中断可能发生在循环中的任何位置(而不是特定的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()

线程的辅助方法具有以下特性:

 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]))

display方法调用以下类的“add\u input\u 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()

Tags: imageselfnewdefnotrootwidthscreen