如何在更改图像后退出tkinter窗口?

时间:2016-10-19 22:40:52

标签: python tkinter

所以我试图用Tkinter做一个小战斗场景,代码应该改变图像,等待几秒钟,然后退出Tkinter窗口。当按下更改图像的按钮时,我刚刚暂停了一下代码。我还是初学者,有些概念很难掌握。 这是代码:

from tkinter import *
import time

class MainWindow():

    def __init__(self, main):

        # canvas for image
        self.canvas = Canvas(main, width=660, height=440)
        self.canvas.grid(row=0, column=0)

        # images
        self.my_images = []
        self.my_images.append(PhotoImage(file = "att1.gif"))
        self.my_images.append(PhotoImage(file = "att2.gif"))
        self.my_image_number = 0
        # set first image on canvas
        self.image_on_canvas = self.canvas.create_image(0, 0, anchor = NW, image = self.my_images[self.my_image_number])

        # button to change image
        self.button = Button(main, text="FIGHT", command=self.onButton)
        self.button.grid(row=1, column=0)

    #----------------

    def onButton(self):

        # next image
        self.my_image_number = 1
        if self.my_image_number == 1:
            time.sleep(2)
            root.quit()
        # change image
        self.canvas.itemconfig(self.image_on_canvas, image = self.my_images[self.my_image_number])

root = Tk()
MainWindow(root)

root.mainloop()

这些代码中的一些是借用的,我试图改变它以符合我的目的

1 个答案:

答案 0 :(得分:1)

图片未更改,因为time.sleep(2)阻止了tkinter更新。睡眠后,tkinter退出,因此图像不会更新。

由于您只有2张图像,并且想要在更改图像后2秒退出tkinter窗口,请尝试:

def onButton(self):
    self.canvas.itemconfig(self.image_on_canvas, image=self.my_images[1])
    root.after(2000, root.destroy) # close root window after 2 seconds