字体错误 - python tkinter标签

问题描述 投票:-1回答:1

即时通讯使用anurati(谷歌,如果你不知道它是什么)字体在胜利10我尝试从tkinter调用它来重现错误

我的代码是:

from tkinter import *

root = Tk()
root.title("P.E.T.A.R")
txt = Label(root, text = "welcome to project petar")
txt.grid(column = 0, row = 0, font=("Anurati Regular"))

而错误是

================ RESTART: C:\Users\dell\Desktop\p.e.t.a.r.py ================
Traceback (most recent call last):
  File "C:\Users\dell\Desktop\p.e.t.a.r.py", line 6, in <module>
    txt.grid(column = 0, row = 0, font=("Anurati Regular", 50))
  File "C:\Users\dell\AppData\Local\Programs\Python\Python35-32\lib\tkinter\__init__.py", line 2082, in grid_configure
    + self._options(cnf, kw))
_tkinter.TclError: bad option "-font": must be -column, -columnspan, -in, -ipadx, -ipady, -padx, -pady, -row, -rowspan, or -sticky
>>> 

为什么会这样呢?

python tkinter fonts label
1个回答
3
投票

你必须先渲染字体,你也错误地使用它。

在开始时使用此代码:

from tkinter import *
import tkinter.font
my_font = tkinter.font.Font(root,family="Anurati Regular")

然后你就可以使用它:

txt = Label(root, text = "welcome to project petar",font=my_font)
txt.grid(column = 0, row = 0)

因此,您的整体代码将如下:

from tkinter import *
import tkinter.font
root = Tk()
root.title("P.E.T.A.R")
my_font = tkinter.font.Font(root,family="Anurati Regular")
txt = Label(root, text = "welcome to project petar",font=my_font)
txt.grid(column = 0, row = 0)

编辑:

正如你在评论中所说的this method does not create the font just a different version of the default,你用不正确的名称调用你的字体或者没有安装字体,当发生这种情况时,tkinter会创建一个基本字体。为了证明这种方法有效,我制作了另一个使用Windows内置字体的代码:

from tkinter import *
import tkinter.font
root = Tk()
root.title("P.E.T.A.R")
my_font = tkinter.font.Font(root,family="Comic Sans MS")
my_font2 = tkinter.font.Font(root,family="Copperplate Gothic Bold")
txt = Label(root, text = "welcome to project petar",font=my_font)
txt.grid(column = 0, row = 0)
txt2 = Label(root, text = "welcome to project petar",font=my_font2)
txt2.grid(column = 0, row = 1)

执行此代码时:

Workig

编辑2:

我做了进一步的调查,下载了Anurati字体,终于意识到我是对的。它有两个问题:

  • 你打错了名字。名字是Anurati,但你使用的是Anurati Regular。你应该使用my_font = tkinter.font.Font(root,family="Anurati")
  • 这种字体的小字母很简单,而资本却不是。并且写过文字是小写字母。你的文字应该是txt = Label(root, text = "WELCOME TO PROJECT PETAR",font=my_font)

之后,您的最终代码变为:

from tkinter import *
import tkinter.font
root = Tk()
root.title("P.E.T.A.R")
my_font = tkinter.font.Font(root,family="Anurati")
txt = Label(root, text = "WELCOME TO PROJECT PETAR",font=my_font)
txt.grid(row=0,column=0)

因此,运行上面的代码后,您将获得预期的输出:qazxsw poi

© www.soinside.com 2019 - 2024. All rights reserved.