Tkinter - 单击按钮时如何显示图像?

时间:2016-08-31 02:01:13

标签: python tkinter

第一次在这里请原谅我,因为这是我第一次尝试制作一个愚蠢的GUI游戏(如果你想称之为)。我试图让用户点击一个按钮,弹出他们选择的图像。我似乎无法弄清楚如何让图像弹出来。

如果我单独运行,图片会显示。

我的代码:

from Tkinter import *

root = Tk()

class PokemonClass(object):
    def __init__(self, master):
        frame = Frame(master)
        frame.pack()

        self.WelcomeLabel = Label(root, text="Welcome! Pick your Pokemon!",
                                  bg="Black", fg="White")
        self.WelcomeLabel.pack(fill=X)

        self.CharButton = Button(root, text="Charmander", bg="RED", fg="White",
                                 command=self.CharClick)
        self.CharButton.pack(side=LEFT, fill=X)

        self.SquirtButton = Button(root, text="Squirtle", bg="Blue", fg="White")
        self.SquirtButton.pack(side=LEFT, fill=X)

        self.BulbButton = Button(root, text="Bulbasaur", bg="Dark Green",
                                 fg="White")
        self.BulbButton.pack(side=LEFT, fill=X)

    def CharClick(self):
        print "You like Charmander!"
        global CharSwitch
        CharSwitch = 'Yes'

CharSwitch = 'No'

if CharSwitch == 'Yes':
    CharPhoto = PhotoImage(file="Charmander.gif")
    ChLabel = Label(root, image=CharPhoto)
    ChLabel.pack()

k = PokemonClass(root)
root.mainloop()

2 个答案:

答案 0 :(得分:0)

这样可行,但实际图像不再显示,如果我保持类的PhotoImage OUT它会打印,但我想让它打印,如果他们点击特定按钮:

preg_match("/^([0-9]|10)(\D*)/", "10");

答案 1 :(得分:0)

您需要维护对PhotoImage对象的引用。不幸的是,tkinter中存在一个不一致的地方,即将Button附加到父窗口小部件会增加引用计数,但是向窗口小部件添加图像不会增加引用计数。因此,当CharPhoto变量超出函数CharClick末尾的范围时,PhotoImage的引用数降为零,并且对象可用于垃圾收集。

如果您在某处保留对图像的引用,它将会出现。当你在全球范围内保留它时,它仍然在整个脚本的范围内,因此出现了。

您可以在PokemonClass对象或Label窗口小部件中保留对它的引用。

以下是这些选项的后期

from Tkinter import *

root = Tk()

class PokemonClass(object):
    def __init__(self, master):
        frame = Frame(master)
        frame.pack()

        self.WelcomeLabel = Label(root, text="Welcome! Pick your Pokemon!",
                                  bg="Black", fg="White")
        self.WelcomeLabel.pack(fill=X)

        self.CharButton = Button(root, text="Charmander", bg="RED", fg="White",
                                 command=self.CharClick)
        self.CharButton.pack(side=LEFT, fill=X)

        self.SquirtButton = Button(root, text="Squirtle", bg="Blue", fg="White")
        self.SquirtButton.pack(side=LEFT, fill=X)

        self.BulbButton = Button(root, text="Bulbasaur", bg="Dark Green",
                                 fg="White")
        self.BulbButton.pack(side=LEFT, fill=X)

    def CharClick(self):
        print "You like Charmander!"
        global CharSwitch
        CharSwitch = 'Yes'
        CharPhoto = PhotoImage(file="Charmander.gif")
        ChLabel = Label(root, image=CharPhoto)
        ChLabel.img = CharPhoto
        ChLabel.pack()

CharSwitch = 'No'

k = PokemonClass(root)
root.mainloop()
相关问题