添加图像后 Python 按钮无法使用

1 投票
2 回答
1816 浏览
提问于 2025-04-18 08:13

当我尝试给按钮添加一张图片时,程序可以运行,但按钮是空白的,无法点击。如果我把 image=Tkinter.PhotoImage(file="C:/TeDOC/OpenFolder.gif") 改成 text='打开目录',那就没问题了,按钮可以正常点击。我不知道为什么一换成图片就不行了。希望有人能帮帮我。

这是我的代码:

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()

2 个回答

0

你必须把这个图片保存在自定义的地方。

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

如果把它删除了,就不会显示出来了。

2

首先,你需要定义你的图片,使用self.image。可以试试这个:

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

然后在你的按钮下面,放上:

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

撰写回答