字体更改菜单按钮不会在 tkinter 文本编辑器中切换字体



在这里的第一篇文章中,作为python的初学者项目,我正在开发一个非常基本的文本编辑器,我已经成功地使它发挥了很大的作用,但我只是不知道如何使字体和字体大小菜单按钮发挥作用。起初,我只有一个按钮将文本切换为Times New Roman,大小为12,而不是默认的Tkinter字体,这很有效,但当我添加了独立更改字体和字号的功能时,它将默认为Calibri大小12(这两个按钮都是代码中最后添加的按钮(,我无法更改字体或大小。有什么想法吗?

问题代码:

def change_font(fontname):
global font
font = fontname
text_info.configure(font=(font, font_size))
def change_font_size(size):
global font_size
font_size = size
text_info.configure(font=(font, font_size))
font_menu = Menu(menubar, tearoff=0)
font_menu.add_command(label="Times New Roman", command=change_font("Times New Roman"))
font_menu.add_command(label="Calibri", command=change_font("Calibri"))
menubar.add_cascade(label="Font", menu=font_menu)
font_size_menu = Menu(menubar, tearoff=0)
for i in range(8, 13):
font_size_menu.add_command(label=str(i), command=change_font_size(i))
menubar.add_cascade(label="Font Size", menu=font_size_menu)

完整代码:

from tkinter import *
def text_opener():
try:
f = open(text_name, "r+")
except FileNotFoundError:
f = open(text_name, "a+")
f.close()
f = open(text_name, "r+")
return f
text_name = input("What is the name of your .txt file? ") + ".txt"
text = text_opener()
root = Tk()
# intended default font and font size
font = "Arial"
font_size = 11
root.title("Text Editor")
root.geometry("640x360")
root.resizable(width=False, height=False)
scrollbar = Scrollbar(root)
scrollbar.pack(side=RIGHT, fill=Y)
text_info = Text(root, yscrollcommand=scrollbar.set, wrap=WORD)
scrollbar.config(command=text_info.yview)
text_info.pack(fill=BOTH)
text_info.insert(INSERT, text.read())
menubar = Menu(root)
filemenu = Menu(menubar, tearoff=0)
def save():
text.seek(0)
text.write(text_info.get("1.0", 'end-1c'))
text.truncate()
filemenu.add_command(label="Save", command=save)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=root.quit)
menubar.add_cascade(label="File", menu=filemenu)
# problem code below
def change_font(fontname):
global font
font = fontname
text_info.configure(font=(font, font_size))
def change_font_size(size):
global font_size
font_size = size
text_info.configure(font=(font, font_size))
font_menu = Menu(menubar, tearoff=0)
font_menu.add_command(label="Times New Roman", command=change_font("Times New Roman"))
font_menu.add_command(label="Calibri", command=change_font("Calibri"))
menubar.add_cascade(label="Font", menu=font_menu)
font_size_menu = Menu(menubar, tearoff=0)
for i in range(8, 13):
font_size_menu.add_command(label=str(i), command=change_font_size(i))
menubar.add_cascade(label="Font Size", menu=font_size_menu)
root.config(menu=menubar)
root.lift()
root.attributes('-topmost', True)
root.after_idle(root.attributes, '-topmost', False)
root.mainloop()
text.close()
要将参数传递到命令中,必须使用lambda函数或分部对象或类似函数。
font_menu.add_command(label="Times New Roman", command=lambda: change_font("Times New Roman"))

最新更新