1

When I try to add and image to the button, the program will run, but the button will be blank and you cannot click on it. If I change image=Tkinter.PhotoImage(file="C:/TeDOC/OpenFolder.gif") to text='Open Directory it works fine and you are able to click the button. I have no idea why when I change it to an img, it does not work. Any help will be appreciated.

Here is my code:

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()
Luke Woodward
  • 63,336
  • 16
  • 89
  • 104

2 Answers2

2

First you have to define your image, using the self.image. So try:

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

Then under your button, put:

Tkinter.Button(self, image=self.image, command=self.askdirectory).pack(**button_opt)
user3692825
  • 116
  • 2
  • 5
  • 13
  • This is a correct solution, but it is worth mentioning in it the reason for needing to register `image` as a class attribute (i.e. because it will get garbage collected otherwise). – ebarr Jun 02 '14 at 02:46
0

You must save the image in self.

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

If it is deleted it will not be displayed.

User
  • 14,131
  • 2
  • 40
  • 59