如何在使用TKinter单击Python中的按钮之前切换图像

时间:2015-09-03 04:54:42

标签: python canvas tkinter

在下面的代码中,我想在按下button1后立即显示picture1.jpg。过了一段时间,我想要显示picture2.jpg。在下列情况下,按下button1后5秒仅显示picture2.jpg。我该如何更换图片?

from Tkinter import *
from PIL import Image, ImageTk
import time

def show_image():
    while True:
        image = Image.open("picture1.jpg")
        tk_img = ImageTk.PhotoImage(image)
        x = canvas.create_image(400, 300, image=tk_img)
        canvas.itemconfigure(x, state=NORMAL)
        # I want to show picture1.jpg now
        time.sleep(5)  #This is a dummy because it takes a while for picture2.jpg
        #Now I can show picture2.jpg
        image = Image.open("picture2.jpg")
        tk_img = ImageTk.PhotoImage(image)
        x = canvas.create_image(400, 300, image=tk_img)
        canvas.itemconfigure(x, state=NORMAL)
        yield

root = Tk()
canvas = Canvas(root, width=850, height=750)
canvas.grid(row=0, column=0)

button1 = Button(
    root, text="Insert next device and then take a picture", command=show_image().next, anchor='w',
    width=50, activebackground="#33B5E5" ,fg = "blue" , font=("Arial", 24))
button1.grid(row=1, column=0)
root.mainloop()

1 个答案:

答案 0 :(得分:0)

首先,作为一般规则,您不应该在GUI的主线程中调用sleep。它会导致整个程序暂停 - 按钮无法正常工作,屏幕无法更新等等。

Tkinter将来可以运行代码。更改图像,然后使用此功能稍后将其更改回来。粗略地说,它看起来像这样:

def show_image(path):
    image = Image.open(path)
    tk_img = ImageTk.PhotoImage(image)
    x = canvas.create_image(400, 300, image=tk_img)

def switch_images():
    show_image("picture1.jpg")
    root.after(5000, show_image, "picture2.jpg")