开发者

Use file like objects for Tk().iconbitmap()

I am writing a program using Tkinter that is to be 开发者_运维问答eventually compiled into an exe using py2exe. I want to include an icon with it for use on the windows. It will be the same one as I have packed as the icon for the exe. Is there a way to include the icon in Tkinter, either by locating the exe file or using a file-like object? I know that win32api can find the current exe file that's running, but I believe that py2exe extracts the original file to temp, and then runs it, so the original exe couldn't be found that way. I also thought of putting it in an include folder, but I don't know if the cwd would be set correctly for that. Thanks for the help in advance!


Tk images have a -data option which lets you embed the image within the code. You just have to base64-encode the image. I think the image has to originally be in the GIF format.

Here's a working example:

import Tkinter as tk
root = tk.Tk()
data = '''R0lGODlhIAAgALMAAAAAAAAAgHCAkC6LV76+vvXeswD/ANzc3DLNMubm+v/6zS9P
          T6Ai8P8A/////////yH5BAEAAAkALAAAAAAgACAAAAS00MlJq7046803AF3ofAYY
          fh8GIEvpoUZcmtOKAO5rLMva0rYVKqX5IEq3XDAZo1GGiOhw5rtJc09cVGo7orYw
          YtYo3d4+DBxJWuSCAQ30+vNTGcxnOIARj3eTYhJDQ3woDGl7foNiKBV7aYeEkHEi
          gnKFkk4ciYaImJqbkZ+PjZUjaJOElKanqJyRrJyZgSKkokOsNYa2q7mcirC5I5Fo
          fsK6hcHHgsSgx4a9yzXK0rrV19gRADs=
       '''
img = tk.PhotoImage(data=data)
label = tk.Label(image=img)
label.pack()
root.mainloop()


You can embedd the icon in the py2exe binary with the icon_resources option

setup(windows=[
    {'script':'toto.py', "icon_resources": [(1, "toto.ico")]},
    ],

Then you can retrieve it with the windows api

import win32gui, win32api, win32con
from ctypes import c_int, windll

hicon = win32gui.CreateIconFromResource(win32api.LoadResource(None, win32con.RT_ICON, 13), True)

and then attach to a window as long as you know his HWND.

windll.user32.SendMessageA(c_int(hwnd), c_int(win32con.WM_SETICON), c_int(win32con.ICON_SMALL), c_int(hicon))

The 13 constant used in the LoadResource has been retrieved with a tool like ResourceHacker. In ResourceHacker, it corresponds to the folder name of the icon. I don't know how it is calculated by py2exe and if there is a way to force this value.

I don't know also if there is a pure TkInter way to do that and if the icon can be used as-is in a tkinter window.

I hope it helps

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜