Python 如何设置 Canvas 文本项的字体大小?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15457504/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to set the font size of a Canvas' text item?
提问by carte
I have the following code:
我有以下代码:
canvas.create_text(x, y, font="Purisa", text= k)
How do I set the font size with a variable named rndfont?
如何使用名为 的变量设置字体大小rndfont?
采纳答案by A. Rodas
For text items, the font size is part of the fontkeyword argument:
对于文本项,字体大小是font关键字参数的一部分:
canvas.create_text(x, y, font=("Purisa", rndfont), text=k)
回答by Abe Karplus
canvas.create_text(x, y, font="Purisa", size=mdfont, text=k)
assuming that mdfontis just an integer, such as
假设这mdfont只是一个整数,例如
mdfont = 10
or
或者
mdfont = int(raw_input("Font size? "))
回答by Ali Alkhatib
fontis an attribute which you can pass in tkinter objects. You pass a tupleindicating the font nameand size, so your code should look more like:
font是您可以在 tkinter 对象中传递的属性。您传递一个元组,指示字体名称和大小,因此您的代码应该看起来更像:
canvas.create_text(x, y, font=("Purisa", 12), text= k)
But you're asking how to make the font size a variable. You should just be able to pass it as a variable the way you would for any other use:
但是您要问如何使字体大小成为变量。您应该能够像任何其他用途一样将其作为变量传递:
rndfont = 12
canvas.create_text(x, y, font=("Purisa", rndfont), text= k)
I just tested it and it seems that if you pass an invalid attribute for that tuple (like pass an empty string where the font name should be), it'll ignore the attribute entirely.
我刚刚测试了它,似乎如果你为那个元组传递一个无效的属性(比如在字体名称应该是的地方传递一个空字符串),它会完全忽略该属性。
回答by Andrew Shi
You create the font size variable:
您创建字体大小变量:
rndfont=12
and display the text on the canvas:
并在画布上显示文本:
canvas.create_text(x,y,font=('Pursia',rndfont),text=k)
The font parameter can be a tuple with the font name, font size, and the special effect(bold, italic...), such as:
字体参数可以是包含字体名称、字体大小和特殊效果(粗体、斜体...)的元组,例如:
font=('Arial',30,'bold italic')

