【问题标题】:can't press image-buttons in python tkinter无法在 python tkinter 中按下图像按钮
【发布时间】:2022-01-18 22:54:51
【问题描述】:

我创建了不存在的 1px 图像,因此我可以将其设置为按钮并按像素设置宽度和高度。但由于某种原因,之后我无法按下按钮。并且由于某种原因,即使不点击它,该功能也会运行。我做错了什么?

class ShowHide:
def show_hide(self, buttons):
    buttons.pack_forget()
    self.show()

class Page(Frame):
def __init__(self, *args, **kwargs):
    Frame.__init__(self, *args, **kwargs)
def show(self):
    self.lift()
def back(self):
    pass

class GPUs(Page):
    def __init__(self, *args, **kwargs):
        Page.__init__(self, *args, **kwargs)

        pixel = PhotoImage(width=1, height=1)
        amd_frame = AMD(self)
        nvidia_frame = NVIDIA(self)
        intel_frame = INTEL(self)
        container = Frame(self)
        amd_frame.place(in_=container, x=0, y=41, relwidth=1, relheight=10)

        amd_button = Button(container, text='AMD', width=(window.winfo_width() // 3),
                            command=lambda: ShowHide.show_hide(amd_frame, container),
                            image=pixel, font=('consolas', 24), compound='c', height=40)

        amd_button.grid(row=0, column=0)
        container.place(x=0, y=0)

【问题讨论】:

  • 这不是一个可运行的示例——缺少太多东西——但我确实想指出一个问题。 ShowHide.show_hide 将其作为类方法调用。它不会有self 参数,因为您没有创建对象。我不确定您希望 self.show() 在该函数中做什么。

标签: python python-3.x tkinter button


【解决方案1】:

问题的根源在于您的pixel 图像是一个局部变量,因此当它超出范围时会被销毁。这似乎抑制了按钮的功能。

最简单的解决方案是将pixel 替换为self.pixel

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多