943,165 Members | Top Members by Rank

Ad:
  • Python Discussion Thread
  • Unsolved
  • Views: 2111
  • Python RSS
Feb 7th, 2010
0

Tkinter, PIL, PNG transparency issue

Expand Post »
Hi, i'm working on simple fullscreen launcher application, to use it with remote on my HTPC media center to launch xbmc, stepmania, nes emulator, etc
I'd like to use png icons with transparency, but there is a problem. In alpha channel of loaded icons i can see the back frame's color instead of PNG image loaded as wallpaper. What's wrong and how to solve that problem?

Here's the code i've wrote so far:

python Syntax (Toggle Plain Text)
  1. try:
  2. import Tkinter as tk
  3. except ImportError:
  4. raise ImportError,"The Tcl/Tk is required to run this program."
  5. try:
  6. from PIL import Image, ImageTk
  7. except ImportError:
  8. raise ImportError,"Please install image module from http://www.pythonware.com/products/pil/"
  9.  
  10. class SimpleLauncher(tk.Tk):
  11. def __init__(self, parent):
  12. tk.Tk.__init__(self,parent)
  13. self.parent = parent
  14. self.width = self.winfo_screenwidth()
  15. self.height = self.winfo_screenheight()
  16. self.initialize()
  17.  
  18. def initialize(self):
  19. backgroundFile = "night.png"
  20. bckImage = Image.open(backgroundFile)
  21. bckImage = bckImage.resize((self.width, self.height), resample=3)
  22.  
  23. background = ImageTk.PhotoImage(bckImage)
  24. obrazek = ImageTk.PhotoImage(Image.open("ff.png"))
  25.  
  26. bckPanel = tk.Label(self, image=background)
  27. bckPanel.pack(side='top', fill='both', expand='yes')
  28. bckPanel.image = background
  29.  
  30. ikona = tk.Label(bckPanel, image=obrazek)
  31. ikona.pack()
  32. ikona.image = obrazek
  33.  
  34. bClose = tk.Button(bckPanel, text = u"EXIT", command = self.buttonClicked)
  35. bClose.pack(pady=10, ipady=10)
  36.  
  37. bClose2 = tk.Button(bckPanel, text = u"EXIT2", command = self.buttonClicked)
  38. bClose2.pack(pady=10, ipady=10)
  39.  
  40. def buttonClicked(self):
  41. self.destroy()
  42.  
  43. def main():
  44. app = SimpleLauncher(None)
  45. app.overrideredirect(1)
  46. w, h = app.winfo_screenwidth(), app.winfo_screenheight()
  47. app.geometry("%dx%d+0+0" % (w, h))
  48. app.mainloop()
  49.  
  50. if __name__ == "__main__":
  51. main()

Using Python 2.6.4 (r264:75706, Jan 25 2010, 08:55:26) on Arch Linux
PIL 1.17


and unpleasant effect:
Attached Thumbnails
Click image for larger version

Name:	zrzut ekranu1.png
Views:	694
Size:	105.5 KB
ID:	13546  
Last edited by neostead; Feb 7th, 2010 at 7:39 pm.
Similar Threads
Reputation Points: 10
Solved Threads: 0
Newbie Poster
neostead is offline Offline
3 posts
since Feb 2010
Feb 8th, 2010
0

dynamic buttons, dynamic actions

I made some modifications to code, but i have another problem, how to add dynamic actions for dynamic buttons?
My app adds buttons from config file, for each button should be separate action. But when i try to call performAction method in that way, i got errors:

Python Syntax (Toggle Plain Text)
  1. Traceback (most recent call last):
  2. File "/home/bagheera/NetBeansProjects/simpleLauncher/src/simplelauncher.py", line 95, in <module>
  3. main()
  4. File "/home/bagheera/NetBeansProjects/simpleLauncher/src/simplelauncher.py", line 88, in main
  5. app = SimpleLauncher(None)
  6. File "/home/bagheera/NetBeansProjects/simpleLauncher/src/simplelauncher.py", line 32, in __init__
  7. self.initialize()
  8. File "/home/bagheera/NetBeansProjects/simpleLauncher/src/simplelauncher.py", line 78, in initialize
  9. tk.Button(bckPanel, image=item["icon"], command = self.performAction(item["exe"])).pack(side="left", padx = defPadx, in_ = bckPanel)
  10. File "/usr/lib/python2.6/lib-tk/Tkinter.py", line 2002, in __init__
  11. Widget.__init__(self, master, 'button', cnf, kw)
  12. File "/usr/lib/python2.6/lib-tk/Tkinter.py", line 1932, in __init__
  13. (widgetName, self._w) + extra + self._options(cnf))
  14. _tkinter.TclError: can't invoke "button" command: application has been destroyed
  15.  

How to pass item["exe"] parameter to performAction method?
Or mb there's other way to perform actions?

here's the modified code:

python Syntax (Toggle Plain Text)
  1. # To change this template, choose Tools | Templates
  2. # and open the template in the editor.
  3.  
  4. __author__="bagheera"
  5. __date__ ="$2010-02-06 13:10:47$"
  6.  
  7. import sys
  8. try:
  9. import Tkinter as tk
  10. except ImportError:
  11. raise ImportError,"The Tcl/Tk is required to run this program."
  12. try:
  13. from PIL import Image, ImageTk
  14. except ImportError:
  15. raise ImportError,"Please install image module from http://www.pythonware.com/products/pil/"
  16.  
  17. class SimpleLauncher(tk.Tk):
  18. def __init__(self, parent):
  19. tk.Tk.__init__(self,parent)
  20. #object's vars
  21. self.parent = parent
  22. self.width = self.winfo_screenwidth()
  23. self.height = self.winfo_screenheight()
  24.  
  25. #default config vars
  26. self.backgroudFile = ""
  27. self.items = []
  28. self.defIcoWidth = 0
  29.  
  30. #init methods
  31. self.parseConfig()
  32. self.initialize()
  33.  
  34. def parseConfig(self):
  35. try:
  36. configFile = open(".slauncher.cfg", 'r')
  37. except IOError:
  38. sys.exit("No config file. Please refer to readme and create .slauncher.cfg file")
  39. else:
  40. for line in configFile:
  41.  
  42. if line.startswith("wallpaper"):
  43. self.backgroudFile = line.split("=")[-1].strip()
  44.  
  45. #build index of icons and actions
  46. elif line.startswith("item"):
  47. iconFile = line.split("=")[-1].strip().split(":")[0].strip()
  48. iconImage = ImageTk.PhotoImage(Image.open(iconFile))
  49. if self.defIcoWidth == 0:
  50. self.defIcoWidth = iconImage.width()
  51. executedCmd = line.split("=")[-1].strip().split(":")[-1].strip()
  52. self.items.append({"icon":iconImage, "exe":executedCmd})
  53.  
  54. def initialize(self):
  55.  
  56. #setting wallpaper
  57. if self.backgroudFile != "":
  58. bckImage = Image.open(self.backgroudFile)
  59. iw, ih = bckImage.size
  60. if iw != self.width and ih != self.height:
  61. bckImage = bckImage.resize((self.width, self.height), resample=3)
  62. background = ImageTk.PhotoImage(bckImage)
  63.  
  64. bckPanel = tk.Label(self, image=background)
  65. bckPanel.pack(side='top', fill='both', expand='yes')
  66. bckPanel.image = background
  67. else:
  68. bckPanel = tk.Label(self)
  69. bckPanel.pack(side='top', fill='both', expand='yes')
  70.  
  71. #define padx for icons
  72. icoCount = len(self.items)
  73. defPadx = (self.width - (icoCount * self.defIcoWidth)) / (icoCount *2) -3
  74. print(defPadx)
  75.  
  76. #placing icons horizontally
  77. for item in self.items:
  78. tk.Button(bckPanel, image=item["icon"], command = self.performAction(item["exe"])).pack(side="left", padx = defPadx, in_ = bckPanel)
  79. # ikona.pack()
  80. # ikona.image = obrazek
  81.  
  82.  
  83. def performAction(self, command):
  84. if command == "quit()":
  85. self.destroy()
  86.  
  87. def main():
  88. app = SimpleLauncher(None)
  89. app.overrideredirect(1)
  90. w, h = app.winfo_screenwidth(), app.winfo_screenheight()
  91. app.geometry("%dx%d+0+0" % (w, h))
  92. app.mainloop()
  93.  
  94. if __name__ == "__main__":
  95. main()
Reputation Points: 10
Solved Threads: 0
Newbie Poster
neostead is offline Offline
3 posts
since Feb 2010
Feb 8th, 2010
0
Re: Tkinter, PIL, PNG transparency issue
Well, i managed to solve second problem, i used dicts with labels references as keys. I don't know what to do with transparency issue

Here's updated code:
python Syntax (Toggle Plain Text)
  1. #!/usr/bin/env python
  2. #-*- coding: utf-8 -*-
  3. # To change this template, choose Tools | Templates
  4. # and open the template in the editor.
  5.  
  6. __author__="bagheera"
  7. __date__ ="$2010-02-06 13:10:47$"
  8.  
  9. import sys
  10. import os
  11. try:
  12. import Tkinter as tk
  13. except ImportError:
  14. raise ImportError,"The Tcl/Tk is required to run this program."
  15. try:
  16. from PIL import Image, ImageTk
  17. except ImportError:
  18. raise ImportError,"Please install image module from http://www.pythonware.com/products/pil/"
  19.  
  20. class SimpleLauncher(tk.Tk):
  21. def __init__(self, parent):
  22. tk.Tk.__init__(self,parent)
  23. #object's vars
  24. self.parent = parent
  25. self.width = self.winfo_screenwidth()
  26. self.height = self.winfo_screenheight()
  27.  
  28. #default config vars
  29. self.backgroudFile = ""
  30. self.items = []
  31. self.createdItems = {}
  32. self.createdIconsNormal = {}
  33. self.createdIconsBig = {}
  34. self.defIcoWidth = 0
  35. self.mouse = "on"
  36.  
  37. #init methods
  38. self.parseConfig()
  39. self.initialize()
  40.  
  41. #load and parse config file
  42. def parseConfig(self):
  43. try:
  44. configFile = open(".slauncher.cfg", 'r')
  45. except IOError:
  46. sys.exit("No config file. Please refer to readme and create .slauncher.cfg file")
  47. else:
  48. for line in configFile:
  49.  
  50. if line.startswith("wallpaper"):
  51. self.backgroudFile = line.split("=")[-1].strip()
  52.  
  53. #build index of icons and actions
  54. elif line.startswith("item"):
  55. iconFile = line.split("=")[-1].strip().split(":")[0].strip()
  56. iconImage = Image.open(iconFile)
  57. w, h = iconImage.size
  58. ws, wh = 30 * w / 100, 30 * h / 100
  59. iconImageBig = iconImage.resize((w + ws, h + wh), resample = 3)
  60. #convert images to Tk objects
  61. iconNormal = ImageTk.PhotoImage(iconImage)
  62. iconBig = ImageTk.PhotoImage(iconImageBig)
  63.  
  64. if self.defIcoWidth == 0:
  65. self.defIcoWidth = iconNormal.width()
  66. executedCmd = line.split("=")[-1].strip().split(":")[-1].strip()
  67. self.items.append({"iconNormal":iconNormal, "iconBig":iconBig, "exe":executedCmd})
  68. elif line.startswith("mouse"):
  69. param = line.split("=")[-1].strip()
  70. if param == "off":
  71. self.mouse = "off"
  72.  
  73. #execute command binded to clicked icon
  74. def executeCmd(self, event):
  75. command = self.createdItems[event.widget]
  76. if command == "quit()":
  77. self.destroy()
  78. else:
  79. self.withdraw()
  80. os.system(command)
  81. self.deiconify()
  82.  
  83. #change image size if mouse pointer is over the icon
  84. def makeActive(self, event):
  85. curButton = event.widget
  86. curButton.configure(image = self.createdIconsBig[curButton])
  87.  
  88. def makeUnActive(self, event):
  89. curButton = event.widget
  90. curButton.configure(image = self.createdIconsNormal[curButton])
  91.  
  92. def initialize(self):
  93. self.overrideredirect(1)
  94. self.geometry("%dx%d+0+0" % (self.width, self.height))
  95. #setting wallpaper
  96. if self.backgroudFile != "":
  97. bckImage = Image.open(self.backgroudFile)
  98. iw, ih = bckImage.size
  99. if iw != self.width and ih != self.height:
  100. bckImage = bckImage.resize((self.width, self.height), resample=3)
  101. background = ImageTk.PhotoImage(bckImage)
  102.  
  103. bckPanel = tk.Label(self, image=background)
  104. bckPanel.pack(side='top', fill='both', expand='yes')
  105. bckPanel.image = background
  106. else:
  107. bckPanel = tk.Label(self)
  108. bckPanel.pack(side='top', fill='both', expand='yes')
  109.  
  110. #define padx for icons
  111. icoCount = len(self.items)
  112. defPadx = (self.width - (icoCount * self.defIcoWidth)) / (icoCount *2) -3
  113.  
  114. #placing icons horizontally
  115. #mouse controlled actions
  116. if self.mouse == "on":
  117. for item in self.items:
  118. button = tk.Label(bckPanel, image=item["iconNormal"])
  119. button.bind("<Button-1>", self.executeCmd)
  120. button.bind("<Enter>", self.makeActive)
  121. button.bind("<Leave>", self.makeUnActive)
  122. button.pack(side="left", padx = defPadx, in_ = bckPanel)
  123. button.image = item["iconNormal"]
  124. self.createdItems[button] = item["exe"]
  125. self.createdIconsNormal[button] = item["iconNormal"]
  126. self.createdIconsBig[button] = item["iconBig"]
  127.  
  128.  
  129. def main():
  130. root = SimpleLauncher(None)
  131. root.mainloop()
  132.  
  133. if __name__ == "__main__":
  134. main()
Reputation Points: 10
Solved Threads: 0
Newbie Poster
neostead is offline Offline
3 posts
since Feb 2010

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
Message:
Previous Thread in Python Forum Timeline: howto create a reasonable library of subroutines
Next Thread in Python Forum Timeline: Help with loops and when they end? for a newbie?





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC