Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
434 views
in Technique[技术] by (71.8m points)

python - How do you make a font dialog in tkinter?

I need help making a font dialog in tkinter.

Here is my code so far:

from tkinter import *

root = Tk()
root.geometry("600x600")

def fontDialog():
    root2 = Toplevel(root)
    root2.geometry("300x300")
    root2.mainloop

button = Button(root, text="font dialog", command=fontDialog)

root.mainloop

So in def fontDialog, I made a screen. I don't know how to make a font dialog that changes the font family and size. If you do please help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A font chooser is very simple to make. All you really do is run a loop on font.families() and insert the return of each iteration into a Listbox. From there, you just tell it to change the family of a persistent font reference to whatever is selected in the Listbox when the Listbox is clicked. The font will change for anything that has the persistent font reference applied to its font option.

import tkinter as tk
from tkinter import font


class App(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)

        #persistent font reference
        textfont = font.Font(family='arial', size='14')
        
        #something to type in ~ uses the persistent font reference
        tk.Text(self, font=textfont).grid(row=0, column=0, sticky='nswe')
        
        #make the textfield fill all available space
        self.grid_rowconfigure(0, weight=1)
        self.grid_columnconfigure(0, weight=1)
        
        #font chooser
        fc = tk.Listbox(self)
        fc.grid(row=0, column=1, sticky='nswe')

        #insert all the fonts
        for f in font.families():
            fc.insert('end', f)

        #switch textfont family on release
        fc.bind('<ButtonRelease-1>', lambda e: textfont.config(family=fc.get(fc.curselection())))
        
        #scrollbar ~ you can actually just use the mousewheel to scroll
        vsb = tk.Scrollbar(self)
        vsb.grid(row=0, column=2, sticky='ns')
        
        #connect the scrollbar and font chooser
        fc.configure(yscrollcommand=vsb.set)
        vsb.configure(command=fc.yview)


if __name__ == "__main__":
    app = App()
    app.title('Font Chooser Example')
    app.geometry(f'800x600+200+200')
    app.mainloop()
    
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...