Is There any way to use google custom fonts in Tkinter Application.
I have google Font zip file from google font and I want to use that in my tkinter application.
I've came to the same problem, unfortunately it doesn't seem to be possible to use custom fonts in traditional way anyways.
But I came to a workaround by making a image with that text onto it.
def create_text_image(self, text, color_rgba_code_tuple):
fnt = Enums.ImageFont.truetype(Enums.FONT_DEFAULT, Enums.FONT_SIZE)
text_width, text_height = fnt.getsize(text)
img = Enums.Image.new('RGBA', (text_width,text_height))
d = Enums.ImageDraw.Draw(img)
d.text((0,0), text, font=fnt,fill=color_rgba_code_tuple)
img.save(Enums.FONT_TEMPORARY_IMAGE_PATH)
return Enums.PhotoImage(file=Enums.FONT_TEMPORARY_IMAGE_PATH)
Imports
from PIL import Image, ImageDraw, ImageFont, ImageTk
Explanation
You need to pass in your text and rgba tuple into the function; so, something like (255,255,255,255) for white text.
And then simply add that image that the function returns to a list, and use it in wherever place you want (like Canvas for example).
Hope this is clear.
I have a chart function that saves the end figure as a file. After I run the function, I also want it to display the figure at the end. So, I use this:
from PIL import Image
filepath = 'image.png'
img = Image.open(filepath)
img.show()
It works just fine, but when the file opens, it opens with a random file name, not the actual file name.
This can get troublesome as I have a lot of different chart functions that work in a similar fashion, so having logical names is a plus.
Is there a way I can open an image file with Python and have it display it's original file name?
EDIT
I'm using Windows, btw.
EDIT2
Updated the example with code that shows the same behaviour.
Instead of PIL you could use this:-
import os
filepath = "path"
os.startfile(filepath)
Using this method will open the file using system editor.
Or with PIL,
import Tkinter as tk
from PIL import Image, ImageTk # Place this at the end (to avoid any conflicts/errors)
window = tk.Tk()
#window.geometry("500x500") # (optional)
imagefile = {path_to_your_image_file}
img = ImageTk.PhotoImage(Image.open(imagefile))
lbl = tk.Label(window, image = img).pack()
window.mainloop()
The function img.show() opens a Windows utility to display the image. The image is first written to a temporary file before it is displayed. Here is the section from the PIL docs.
https://pillow.readthedocs.io/en/stable/reference/Image.html#PIL.Image.Image.show
Image.show(title=None, command=None)[source] Displays this image. This
method is mainly intended for debugging purposes.
This method calls PIL.ImageShow.show() internally. You can use
PIL.ImageShow.register() to override its default behaviour.
The image is first saved to a temporary file. By default, it will be
in PNG format.
On Unix, the image is then opened using the display, eog or xv
utility, depending on which one can be found.
On macOS, the image is opened with the native Preview application.
On Windows, the image is opened with the standard PNG display utility.
Parameters title – Optional title to use for the image window, where
possible.
"
The issue is that PIL uses a quick-and-dirty method for showing your image, and it's not intended for serious application use.
I am making an animated presentation and I want to add an image to it, but I can't use PIL because it will be presented at school, where PIL isn't installed, so I used the method given by the website http://effbot.org/pyfaq/why-do-my-tkinter-images-not-appear.htm, but it doesn't work - my slide is still blank. What should I do?
Here is my code (copied almost completely from the website - did I miss something out?):
photo = PhotoImage('Alveoli.png')
label = Label(image=photo)
label.image = photo # keep a reference!
label.pack()
You can not open .png files without using an external image library. Since PIL isn't available I'd think other similar libraries aren't either.
EDIT: Note: PNG files are supported for tkinter v8.6+.
The only possibility that comes to mind is converting the image to another, compatible format like GIF or PGM
If you have the image in one of those formats you can simply add them. It worked just fine for me with this code:
from tkinter import *
root = Tk()
photo = PhotoImage(file="img.ppm")
img = Label(root, image=photo)
img.image = photo
img.place(x=0, y=0)
root.mainloop()
How to remove tkinter icon from title bar in it's window
On Windows
Step One:
Create a transparent icon using either an icon editor, or a site like rw-designer. Save it as transparent.ico.
Step Two:
from tkinter import *
tk = Tk()
tk.iconbitmap(default='transparent.ico')
lab = Label(tk, text='Window with transparent icon.')
lab.pack()
tk.mainloop()
On Unix
Something similar, but using an xbm icon.
Similar to the accepted answer (with the con of being uglier):
import tkinter
import tempfile
ICON = (b'\x00\x00\x01\x00\x01\x00\x10\x10\x00\x00\x01\x00\x08\x00h\x05\x00\x00'
b'\x16\x00\x00\x00(\x00\x00\x00\x10\x00\x00\x00 \x00\x00\x00\x01\x00'
b'\x08\x00\x00\x00\x00\x00#\x05\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
b'\x00\x01\x00\x00\x00\x01') + b'\x00'*1282 + b'\xff'*64
_, ICON_PATH = tempfile.mkstemp()
with open(ICON_PATH, 'wb') as icon_file:
icon_file.write(ICON)
tk = tkinter.Tk()
tk.iconbitmap(default=ICON_PATH)
label = tkinter.Label(tk, text="Window with transparent icon.")
label.pack()
tk.mainloop()
It just creates the file on the fly instead, so you don't have to carry an extra file around. Using the same method, you could also do an '.xbm' icon for Unix.
Edit: The ICON can be shortened even further thanks to #Magnus Hoff:
import base64, zlib
ICON = zlib.decompress(base64.b64decode('eJxjYGAEQgEBBiDJwZDBy'
'sAgxsDAoAHEQCEGBQaIOAg4sDIgACMUj4JRMApGwQgF/ykEAFXxQRc='))
Based on previous responses i used this solution:
from PIL import ImageTk
import zlib,base64
import Tkinter
icon=zlib.decompress(base64.b64decode('eJxjYGAEQgEBBiDJwZDBy'
'sAgxsDAoAHEQCEGBQaIOAg4sDIgACMUj4JRMApGwQgF/ykEAFXxQRc='))
root=Tkinter.Tk()
image=ImageTk.PhotoImage(data=icon)
root.tk.call('wm', 'iconphoto', root._w, image)
root.mainloop()
As far as I know, the closest you will get to a "blank" icon is using one that's the same color as the window title bar. But then again a lot of users use different color themes, so it won't go over very well.
However if you use py2exe you can use something like Resource Hacker to swap the icon. But in the python programs text state, the best you can do is replace. Sort of how Jar files use the java icon, tkinter apps will have the TK icon. After all...like java, your app is being translated by an intermediate program. Since another program is running your code, you have to modify that other program. Luckily python/tk is a bit more flexible than the JVM in terms of icons so you can replace the icon. But removing it entirely isn't currently an option.
-John
Alternative to #ubomb's solution for adding custom images by utilizing Tkinter.PhotoImage's built-in support for processing .gif images.
From file:
icon = Tkinter.PhotoImage(file="logo.gif")
from base64:
gif_base64_string = """ R0lGODdhEAAQAIcAAAAAAAEBAQICAgMDAwQEBAUFBQYGBgcHBwgICAkJCQoKCgsLCwwMDA0NDQ4O Dg8PDxAQEBERERISEhMTExQUFBUVFRYWFhcXFxgYGBkZGRoaGhsbGxwcHB0dHR4eHh8fHyAgICEh ... 4B8AAP9Ci/4HoLTpfwD+qV4NoHVAADs= """
icon = Tkinter.PhotoImage(data=gif_base64_string)
Visit the undermentioned link for more details:
//effbot.org/tkinterbook/photoimage.htm
Update:
The slightly modified code (try clause instead of if TkVersion) produces a transparent (no) icon on:
Linux (Mint 18.1), Python 2.7
Linux (Mint 18.1), Python 3.5.1
Windows 10, Python 2.7.13
It produces a black icon (does not work) on:
Windows 8.1, Python 3.6
A rather old question, but the solutions weren't working for me. I found a partial simple solution, with a follow-up question of my own.
The partial solution (Tk 8.5, see below) - using PhotoImage's blank() method:
from Tkinter import *
root=Tk()
icon=PhotoImage(height=16, width=16)
icon.blank()
root.tk.call('wm', 'iconphoto', self.master._w, icon)
root.mainloop()
On Python 2.7, Windows 10, this works fine, producing the desired "no icon" for your new app.
However, on Python 3.6, Win 8.1, this jams the GUI, which I think is related to the newer Tk 8.6, and though I found that the new 8.6 notation of using wm_iconphoto() does pass unjammed in this case:
try:
from tkinter import *
except:
from Tkinter import *
root=Tk()
#Identical for Py2.7/Tk8.5 and Py3.5/Tk8.6
icon=PhotoImage(height=16, width=16)
icon.blank()
#Picking a notaion based on Tk version to avoid jamming
try:
root.wm_iconphoto('True', icon) #New Tk 8.6 style
else:
#Jams Python 3.5 with Tk 8.6 on Windows
root.tk.call('wm', 'iconphoto', self.master._w, icon)
root.mainloop()
It produces a black icon on 3.6, instead of the transparent one in case of 2.7/8.5.
There might be a way to set the pixels transparent one by one using "transparency set" -
http://wiki.tcl.tk/1449
However, I don't know if it's even doable via Tkinter. God favors the bold, someone else's turn though?
Updated question: Why doesn't this work on Py3.6/Windows?
Recently, I've found a solution for Linux in an old Ubuntu forum's post.
The solution makes use of iconbitmap and iconmask with a blank (filled with zeroes) .xbm file.
So, first of all, what is a .xbm file?
A .xbm file is a plain text (it's actually C code !) image format commonly used for storing bitmaps, the data is stored as a 2D Matrix (a two-dimensional array, or an array of arrays)
with 8-bits (256 possible values, from 0 to 255) sized elements, the Matrix is represented as a single one-dimensional array plus values that define it's shape.
The data can be interpreted in any way, but it is usually interpreted as a monochrome/grayscale image.
iconbitmap
Our first method is called iconbitmap and is used to set a bitmap as the icon of our tkinter window, we can input the location of a .xbm file and it will be represented as
a monochrome/grayscale icon, where the pixels/elements of the .xbm represent different grayscale levels, remember the pixels/elements are 8-bits values
in the range 0-255, so the value 0 will be represented as black and 255 will be represented as white and the other values are going to be interpolations between the two values.
iconmask
Our second method is called iconmask and here is where the magic happens, it is used to set alpha/transparency values to the pixels of our window's icon,
we can input the location of a .xbm file and elements with value 0 in the .xbm will be set as fully transparent, I've tested it on Debian with xfce4 and the transparency values
don't seem to interpolate linearly in the range 0-255.
Our Solution
With that information we can create a transparent icon with tkinter in the following way:
import tkinter
tk = tkinter.Tk()
# Your file path has to start with an "#" otherwise the methods will raise an exception.
xbm_location = "#blank.xbm"
# Here we call the iconbitmap method with the xbm location, since it's a blank xbm (filled with zeroes) it will be represented as a black icon.
tk.iconbitmap(xbm_location)
# Here we call the iconmask method with xbm location, since it's a blank xbm (filled with zeroes) it will be represented as a fully transparent icon.
tk.iconmask(xbm_location)
And there is our solution, I've also tested it on Windows and the system seems to just ignore the iconmask method, so stick with the other solutions for your Windows code.
Another possible solution is using the method iconphoto with a PhotoImage loaded from a fully transparent .gif file or even create a blank PhotoImage as suggested by Jay,
but it also doesn't seem to work properly on Windows.
How to create a blank .xbm?
It's pretty easy to create a blank .xbm, just download a .xbm file, create from scratch, or convert an image to .xbm and if the .xbm is not blank (filled with zeroes) already, open the .xbm
in a text editor and replace all the values inside the array with "0x00".
Conclusion
That's it, A blank .xbm, iconbitmap and iconmask. Now you should be able to create fully transparent icons in a tkinter window on Linux...
Hooray !
I have an issue with writing text to an image under Python and PIL -
I'm able to write text to a png file, though not bold text. Could anyone provide an example of how to achieve this?
I thought the easiest solution may be was use a bold-variant of a text, but I'm unable to see anything in the Windows/font folder that supplies this - does this mean font types have a 'bold attribute' that is T/F?:
Code I'm using:
import PIL
from PIL import ImageFont
from PIL import Image
from PIL import ImageDraw
# font = ImageFont.truetype("Arial-Bold.ttf",14)
font = ImageFont.truetype("Arial.ttf",14)
img=Image.new("RGBA", (500,250),(255,255,255))
draw = ImageDraw.Draw(img)
draw.text((0, 0),"This is a test",(0,0,0),font=font)
draw = ImageDraw.Draw(img)
img.save("a_test.png")
A simple way to do it:
font = ImageFont.load_default().font
Also you can do a google search for 'verdana.ttf' and download it put it in the same directory as the python file:
Then add it like this:
font = ImageFont.truetype("Verdana.ttf",14)
You aren't looking at actual font files in the control panel (explorer magically turns into the font viewer control panel when in the Windows/fonts folder as well), they are grouped by family for your convenience. Double click the family to see the fonts in the family:
Then right-click and choose properties to find the file name: