/image_button.py

https://github.com/jasoncbautista/Focus-Motivator
Python | 49 lines | 20 code | 9 blank | 20 comment | 2 complexity | 93b8486527937d9ff52ebbbf29df6f1d MD5 | raw file
  1. # create a Tkinter button with an image and optional text
  2. # note that Tkinter reads only GIF and PGM/PPM images
  3. # for other image file types use the Python Image Library (PIL)
  4. # replace the line photo1 = tk.PhotoImage(file="Press1.gif")
  5. # with these three lines ...
  6. #
  7. # from PIL import Image, ImageTk
  8. # image1 = Image.open("Press1.jpg")
  9. # photo1 = ImageTk.PhotoImage(image1)
  10. #
  11. # tested with Python24 vegaseat 23dec2006
  12. import Tkinter as tk
  13. button_flag = True
  14. def click():
  15. """
  16. respond to the button click
  17. """
  18. print 'Click!'
  19. global button_flag
  20. # toggle button colors as a test
  21. if button_flag:
  22. button1.config(bg="white")
  23. button_flag = False
  24. else:
  25. button1.config(bg="green")
  26. button_flag = True
  27. root = tk.Tk()
  28. # create a frame and pack it
  29. frame1 = tk.Frame(root)
  30. frame1.pack(side=tk.TOP, fill=tk.X)
  31. # pick a (small) image file you have in the working directory ...
  32. photo1 = tk.PhotoImage(file="cars.gif")
  33. # create the image button, image is above (top) the optional text
  34. button1 = tk.Button(frame1, compound=tk.TOP, width=155, height=155, image=photo1,
  35. text="optional text", bg='green', command=click)
  36. button1.pack(side=tk.LEFT, padx=1, pady=2)
  37. # save the button's image from garbage collection (needed?)
  38. button1.image = photo1
  39. # start the event loop
  40. root.mainloop()