如何在tkinter中创建字体对话框?

2024-03-29 06:39:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要帮助在tkinter中创建字体对话框

以下是我目前的代码:

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

所以在对话框中,我制作了一个屏幕。我不知道如何创建一个字体对话框来更改字体系列和大小。如果你愿意,请帮忙


Tags: 代码fromimporttkinterdef字体buttonroot
1条回答
网友
1楼 · 发布于 2024-03-29 06:39:57

字体选择器制作起来非常简单。您真正要做的就是在font.families()insert上运行一个循环,将每个迭代返回到Listbox。从那里,您只需告诉它在单击Listbox时,将持久字体引用的family更改为在Listbox中选择的内容。如果将持久字体引用应用于font选项,则字体将更改

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()
    
    

相关问题 更多 >