Python tkinter class 2按钮,只有1个可见

时间:2018-06-04 14:02:21

标签: python class tkinter

我在python tkinter中编写了一个类,您可以使用它创建在休假,输入和按钮1事件中更改其图像的按钮。

剧本:

from tkinter import *

class ImageButton:

    def CreateButton(self, image, root):
        # --- image setup ---
        self.ImageName = image
        self.ButtonRoot = root
        self.normal = PhotoImage(file="Images/" + self.ImageName + "/normal.png")
        self.hover = PhotoImage(file="Images/" + self.ImageName + "/hover.png")
        self.clicked = PhotoImage(file="Images/" + self.ImageName + "/clicked.png")
        # --- button setup ---
        self.Button = Button(self.ButtonRoot, image=self.normal)
        self.Button.bind("<Leave>", self.normal_event)
        self.Button.bind("<Enter>", self.hover_event)
        self.Button.bind("<Button-1>", self.click_event)
        return self.Button

    def normal_event(self, event):
        self.Button.config(image=self.normal)

    def hover_event(self, event):
        self.Button.config(image=self.hover)

    def click_event(self, event):
        self.Button.config(image=self.clicked)


Root = Tk()
Image = ImageButton()


FirstButton = Image.CreateButton("scann_device", Root)
FirstButton.grid(row=0, column=0)

SecondButton = Image.CreateButton("get_device_info", Root)
SecondButton.grid(row=1, column=0)

Root.mainloop()

因此,如果您使用该类创建按钮,则可以执行任何操作。它只会将它与我上面提到的事件联系起来。如果你创建了1个按钮,它可以工作,你可以在窗口看到它,但如果你创建2个按钮并网格/打包它们,它就不会工作。它看起来像this。第二个按钮也会获得第一个按钮的命中框。

1 个答案:

答案 0 :(得分:0)

您只启动Image的一个实例。因此,在您第二次调用CreateButton()时,所有类对象(self.normalself.ImageNameself.Button)都会被新值覆盖。

最好从tkinter Button继承一个类并添加自己的函数。见这个例子:

from tkinter import *

class ImageButton(Button):

    def __init__(self, image, root, *args, **kwargs):
        super().__init__(root, *args, **kwargs)
        # --- image setup ---
        self.image_name = image
        self.normal = PhotoImage(file="Images/" + self.image_name + "/normal.png")
        self.hover = PhotoImage(file="Images/" + self.image_name + "/hover.png")
        self.clicked = PhotoImage(file="Images/" + self.image_name + "/clicked.png")
        # --- button setup ---
        self.config(image=self.normal)
        self.bind("<Leave>", self.normal_event)
        self.bind("<Enter>", self.hover_event)
        self.bind("<Button-1>", self.click_event)

    def normal_event(self, event):
        self.config(image=self.normal)

    def hover_event(self, event):
        self.config(image=self.hover)

    def click_event(self, event):
        self.config(image=self.clicked)


root = Tk()

FirstButton = ImageButton("scann_device", root)
FirstButton.grid(row=0, column=0)

SecondButton = ImageButton("get_device_info", root)
SecondButton.grid(row=1, column=0)

root.mainloop()