I was just curious if there's a way I can have every option in my OptionMenu have a different font?So in my case, each option would have it's respective font. So far all I could find online is just setting all the options to the same font. Here is my code: EDIT: I got it where I can see the correct font only after I click though.
# function for font selection
def selectedFont(name, index, mode):
#fontLabel = tkinter.Label(top, text = font_clicked.get()).pack()
global font_path
if font_clicked.get() == 'Calibri':
font_path = "C:\Windows\Fonts\calibri.ttf"
dropDown.config(font = ('Calibri', 12))
return font_path
elif (font_clicked.get() == 'Comic Sans'):
font_path = "C:\Windows\Fonts\comic.ttf"
dropDown.config(font = ('Comic Sans MS', 12))
return font_path
elif (font_clicked.get() == 'Broadway'):
font_path = "C:\Windows\Fonts\BROADW.ttf"
dropDown.config(font = ('Broadway', 12))
return font_path
elif (font_clicked.get() == 'STENCIL'):
font_path = "C:\Windows\Fonts\STENCIL.ttf"
dropDown.config(font = ('Stencil', 12))
return font_path
elif (font_clicked.get() == 'Blackadder ITC'):
font_path = "C:\Windows\Fonts\ITCBLKAD.ttf"
dropDown.config(font = ('Blackadder ITC', 12))
return font_path
# options for font selection
optionsFont = [
"Calibri",
"Comic Sans",
"Broadway",
"STENCIL",
"Blackadder ITC"
]
#### drop down menu ####
font_clicked = tkinter.StringVar()
font_clicked.set(optionsFont[0])
dropDown = tkinter.OptionMenu(top, font_clicked, *optionsFont)
dropDown["menu"].config(bg="light pink", fg="black")
dropDown.config(bg = "gray81")
dropDown.pack()
dropDown.place(x=50,y=108, height = 30, width = 250)
Callbackname = font_clicked.trace_variable('w', selectedFont)
Yes, it is possible to change the font of each item in an option menu but make sure that font is compatible with Tkinter otherwise it won't show up, you can check all the fonts compatible with Tkinter by
import tkinter as tk
import tkinter.font as font
root = tk.Tk()
print(list(font.families()))
Now to change each font in the optionmenu we use entryconfigure
method of the menu linked with the optionmenu widget can be accessed by its object ( op['menu']
). The menu of optionmenu has all the options of a Tkinter Menu.
Take a look at this example.
import tkinter as tk
import tkinter.font as font
root = tk.Tk()
root.geometry('200x150')
var = tk.StringVar()
op = tk.OptionMenu(root, var, *font.families())
op.pack(pady=20)
lb = tk.Label(root, textvariable=var)
lb.pack()
for item in range(0, int(op['menu'].index('end'))):
op['menu'].entryconfig(item, font=font.Font(family=font.families()[item]))
var.trace('w', lambda *a: lb.config(font=op['menu'].entrycget(var.get(),'font')))
root.mainloop()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.