按下按钮后如何显示图像?

时间:2019-04-28 22:18:43

标签: python image button tkinter

我正在尝试做一个记忆游戏,我希望在按下按钮后显示图像。就像现在的代码一样,图像立即出现。我确信有一种简单的方法可以使图像在按下时看起来好像在按钮的“后面”,但是由于我是初学者,因此无法正常工作。有没有人可以给我一些建议?

from tkinter import *
from PIL import Image, ImageTk

root=Tk()

topFrame=Frame(root)
topFrame.pack()
bottomFrame=Frame(root)
bottomFrame.pack(side=BOTTOM)

def showImage(kitten):
        if kitten == 1:
                load1 = Image.open('Kittens1.GIF')
                render1 = ImageTk.PhotoImage (load1)

                img1 = Label(image=render1)
                img1.image = render1
                img1.pack()

        if kitten == 2:
                load1 = Image.open('Kittens2.GIF')
                render1 = ImageTk.PhotoImage (load1)

                img1 = Label(image=render1)
                img1.image = render1
                img1.pack()        

def kitten(button):
        if button == 1:
                picture = showImage(1)
                return picture

        if button == 2:
                picture = showImage(2)
                return picture

        if button == 3:
                picture = showImage(3)
                return picture
        if button == 4:
                picture = showImage(4)
                return picture

        if button == 5:
                picture = showImage(5)
                return picture       

        if button == 6:
                picture = showImage(6)
                return picture       

number1 = 1
number2 = 2
number3 = 3
number4 = 4
number5 = 5
number6 = 6


button1= Button(topFrame, text="button1", fg="red", command=kitten(number1))
button2= Button(topFrame, text="button2", fg="blue", command=kitten(number2))
button3= Button(topFrame, text="button3", fg="green", command=kitten(number3))
button4= Button(bottomFrame, text="button4", fg="purple", command=kitten(number4))
button5= Button(bottomFrame, text="button5", fg="orange", command=kitten(number5))
button6= Button(bottomFrame, text="button6", fg="yellow", command=kitten(number6))

#packar dem för att visa dem. För att få dem efter varandra på en rad, skriv side=LEFT. annars packas de bara uppe på varandra.
button1.pack(side=LEFT)
button2.pack(side=LEFT)
button3.pack(side=LEFT)
button4.pack(side=LEFT)
button5.pack(side=LEFT)
button6.pack(side=LEFT)


root.mainloop()

1 个答案:

答案 0 :(得分:1)

创建按钮时,如果您调用该函数,则该回调函数将立即运行,即,该函数名以括号结尾:command=kitten(number1)。通常,您只需提供不带括号的函数名称即可。

要使用按钮中的参数调用函数,可以使用lambda,请参见下面的示例:

button1= Button(topFrame, text="button1", fg="red", 
                command=lambda: kitten(number1))