pythontkinter:通过按按钮将图像按钮替换为图像标签

2024-10-03 06:22:45 发布

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

我正在尝试将图像按钮更改为图像标签。按下按钮应将按钮的图像更改为与其他图像一起标记。之后,它应该仍然可以按下其他图像按钮。在

我有我从这里得到的代码:Python tkinter: Replacing an image button with an image label

from tkinter import *

class Game:
    def __init__(self):
        self.__window = Tk()

        self.gifdir = "./"

        self.igm = PhotoImage(file=self.gifdir+"empty.gif")

        self.btn = Button(self.__window, image=self.igm, command = self.change_picture)
        self.btn.grid(row=1, column=2, sticky=E)
        self.btn2 = Button(self.__window, image=self.igm, command = self.change_picture)
        self.btn2.grid(row=1, column=1, sticky=E)

        self.__window.mainloop()

    def change_picture(self):
        self.igm = PhotoImage(file=self.gifdir+"new.gif")
        self.btn.configure(image = self.igm)


def main():
    Game()


main()

如果我按另一个按钮,我就不能再按另一个按钮了,我想把按下的按钮改成标签。在


Tags: 图像imageselfangametkinterdef标签
1条回答
网友
1楼 · 发布于 2024-10-03 06:22:45

我修改了代码,为按钮和图像使用多个引用:

from tkinter import *

class Game:
    def __init__(self):
        self.__window = Tk()

        self.gifdir = "./"


        self.imgs = [PhotoImage(file=self.gifdir+"empty.gif"), 
                     PhotoImage(file=self.gifdir+"empty.gif")]
        self.btns = []


        btn1 = Button(self.__window, image=self.imgs[0], 
                           command = lambda: self.change_picture(0))
        btn1.grid(row=1, column=2, sticky=E)

        self.btns.append(btn1)

        btn2 = Button(self.__window, image=self.imgs[1], 
                            command = lambda: self.change_picture(1))
        btn2.grid(row=1, column=1, sticky=E)

        self.btns.append(btn2)

        self.__window.mainloop()

    def change_picture(self, btn_no):
        self.imgs[btn_no] = PhotoImage(file=self.gifdir+"new.gif")
        self.btns[btn_no].configure(image = self.imgs[btn_no])



def main():
    Game()  

main()

对按钮和图像的引用存储在列表中。更改图片被更改为以按钮编号为参数,以便您可以区分是哪个按钮被按下。在

有了这些变化,每个按钮都可以单独按下,这样当按下时图像就会发生变化。在

相关问题 更多 >