【问题标题】:python button does not work when image is added [duplicate]添加图像时python按钮不起作用[重复]
【发布时间】:2014-07-21 22:28:57
【问题描述】:

当我尝试向按钮添加图像时,程序将运行,但按钮将是空白的,您无法单击它。如果我将 image=Tkinter.PhotoImage(file="C:/TeDOC/OpenFolder.gif") 更改为 text='Open Directory 它工作正常,您可以单击该按钮。我不知道为什么当我将其更改为 img 时,它不起作用。任何帮助将不胜感激。

这是我的代码:

import Tkinter, Tkconstants, tkFileDialog

class TkFileDialogExample(Tkinter.Frame):

def __init__(self, root):

Tkinter.Frame.__init__(self, root)

# options for buttons
button_opt = {'fill': Tkconstants.BOTH, 'padx': 5, 'pady': 5}

# define buttons
Tkinter.Button(self, image=Tkinter.PhotoImage(file="C:/TeDOC/OpenFolder.gif"), command=self.askdirectory).pack(**button_opt)

# defining options for opening a directory
self.dir_opt = options = {}
options['initialdir'] = 'C:\\'
options['mustexist'] = False
options['parent'] = root
options['title'] = 'This is a title'


def askdirectory(self):
#Returns a selected directoryname.
return tkFileDialog.askdirectory(**self.dir_opt)

if __name__=='__main__':
  root = Tkinter.Tk()
  TkFileDialogExample(root).pack()
  root.mainloop()

【问题讨论】:

    标签: python image python-2.7 tkinter photoimage


    【解决方案1】:

    首先您必须使用 self.image 定义您的图像。所以试试:

    self.image = Tkinter.PhotoImage(file="C:/TeDOC/OpenFolder.gif")
    

    然后在你的按钮下,放:

    Tkinter.Button(self, image=self.image, command=self.askdirectory).pack(**button_opt)
    

    【讨论】:

    • 这是一个正确的解决方案,但值得一提的是需要将image注册为类属性的原因(即因为否则它将被垃圾收集)。
    【解决方案2】:

    您必须将图像保存在自己中。

    self.image = Tkinter.PhotoImage(file="C:/TeDOC/OpenFolder.gif")
    Tkinter.Button(..., image=Tkinter.PhotoImage(file="C:/TeDOC/OpenFolder.gif"), ...
    

    如果被删除就不会显示了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-27
      • 2019-02-13
      • 2017-02-12
      相关资源
      最近更新 更多