如何在 tkinter 中制作字体对话框?

我需要帮助在 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 中,我做了一个屏幕。我不知道如何制作一个更改字体系列和大小的字体对话框。如果你愿意,请帮忙。


阿晨1998
浏览 159回答 1
1回答

尚方宝剑之说

字体选择器的制作非常简单。您真正要做的就是运行一个循环font.families()并将insert每次迭代返回到Listbox. 从那里,您只需告诉它将持久字体引用的 更改为单击时family选择的任何内容。对于将持久字体引用应用于其选项的任何内容,字体都会发生变化。ListboxListboxfontimport tkinter as tkfrom tkinter import fontclass App(tk.Tk):&nbsp; &nbsp; def __init__(self):&nbsp; &nbsp; &nbsp; &nbsp; tk.Tk.__init__(self)&nbsp; &nbsp; &nbsp; &nbsp; #persistent font reference&nbsp; &nbsp; &nbsp; &nbsp; textfont = font.Font(family='arial', size='14')&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; #something to type in ~ uses the persistent font reference&nbsp; &nbsp; &nbsp; &nbsp; tk.Text(self, font=textfont).grid(row=0, column=0, sticky='nswe')&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; #make the textfield fill all available space&nbsp; &nbsp; &nbsp; &nbsp; self.grid_rowconfigure(0, weight=1)&nbsp; &nbsp; &nbsp; &nbsp; self.grid_columnconfigure(0, weight=1)&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; #font chooser&nbsp; &nbsp; &nbsp; &nbsp; fc = tk.Listbox(self)&nbsp; &nbsp; &nbsp; &nbsp; fc.grid(row=0, column=1, sticky='nswe')&nbsp; &nbsp; &nbsp; &nbsp; #insert all the fonts&nbsp; &nbsp; &nbsp; &nbsp; for f in font.families():&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; fc.insert('end', f)&nbsp; &nbsp; &nbsp; &nbsp; #switch textfont family on release&nbsp; &nbsp; &nbsp; &nbsp; fc.bind('<ButtonRelease-1>', lambda e: textfont.config(family=fc.get(fc.curselection())))&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; #scrollbar ~ you can actually just use the mousewheel to scroll&nbsp; &nbsp; &nbsp; &nbsp; vsb = tk.Scrollbar(self)&nbsp; &nbsp; &nbsp; &nbsp; vsb.grid(row=0, column=2, sticky='ns')&nbsp; &nbsp; &nbsp; &nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; #connect the scrollbar and font chooser&nbsp; &nbsp; &nbsp; &nbsp; fc.configure(yscrollcommand=vsb.set)&nbsp; &nbsp; &nbsp; &nbsp; vsb.configure(command=fc.yview)if __name__ == "__main__":&nbsp; &nbsp; app = App()&nbsp; &nbsp; app.title('Font Chooser Example')&nbsp; &nbsp; app.geometry(f'800x600+200+200')&nbsp; &nbsp; app.mainloop()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python