你如何在 tkinter 中制作字体对话框? [英] How do you make a font dialog in tkinter?

查看:88
本文介绍了你如何在 tkinter 中制作字体对话框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要帮助在 tkinter 中制作字体对话框.

I need help making a font dialog in 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

所以在 def fontDialog 中,我做了一个屏幕.我不知道如何制作更改字体系列和大小的字体对话框.如果你这样做,请帮忙.

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.

推荐答案

字体选择器制作起来非常简单.你真正要做的就是在 font.families() 上运行一个循环,然后 insert 将每次迭代的返回值放入一个 Listbox.从那里,您只需告诉它在单击 Listbox 时将持久字体引用的 family 更改为 Listbox 中选择的任何内容.对于将持久字体引用应用于其 font 选项的任何内容,字体都会更改.

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

这篇关于你如何在 tkinter 中制作字体对话框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆