Search code examples
pythonimagepython-2.7tkinterphotoimage

python button does not work when image is added


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

Solution

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