tkinter选项卡宽度不正确
当使用create_text
方法在画布上创建文本时,选项卡的宽度不是应有的,如font.measure
所示。
import tkinter as tk
from tkinter.font import Font
root = tk.Tk()
canvas = tk.Canvas(root, width=300, height=300)
canvas.pack()
font = Font(family='Arial', size=12)
s1 = "a\tb"
s2 = "a c"
print("Width:", s1, font.measure(s1)) # Width: a b 30
print("Width:", s2, font.measure(s2)) # Width: a c 33
canvas.create_text(10, 10, text=s1, font=font, anchor="nw")
canvas.create_text(10, 50, text=s2, font=font, anchor="nw")
root.mainloop()
font.measure
的结果表明,带有空格的行应该更长一些,但是它显示的是:
表明该宽度的宽度标签明显大于空间。使用不同的字体将导致大小不同的选项卡,但仍不准确的测量值。没有标签的文本的测量宽度是正确的。
如何获得正确的标签宽度?这是一个错误吗?
When creating text on a canvas using the create_text
method the width of a tab is not what it should be, as indicated by font.measure
.
import tkinter as tk
from tkinter.font import Font
root = tk.Tk()
canvas = tk.Canvas(root, width=300, height=300)
canvas.pack()
font = Font(family='Arial', size=12)
s1 = "a\tb"
s2 = "a c"
print("Width:", s1, font.measure(s1)) # Width: a b 30
print("Width:", s2, font.measure(s2)) # Width: a c 33
canvas.create_text(10, 10, text=s1, font=font, anchor="nw")
canvas.create_text(10, 50, text=s2, font=font, anchor="nw")
root.mainloop()
The results of font.measure
suggest that the line with spaces should be a little longer, but what it displays is:
Showing that the width of the tab is significantly larger than the spaces. Using different fonts will result in differently sized tabs, but still inaccurate measurements. The measured width of the text without tabs is correct.
How can I get the correct tab width? Is this a bug?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您突出显示的问题是由于没有
tabs
属性的帆布文本对象。也许有人知道如何解决这个问题,但是通常在显示列表时使用
tk.text
对象,其中具有font
和tabs
属性。因此,最简单的解决方案是制作
tk.text
对象t,定义字体和选项卡,将您的消息插入t,然后将t插入
canvas
窗口w。
The problem you've highlighted is due to the Canvas text object not having a
tabs
attribute.Maybe someone knows how to work around that but usually when displaying tabulation a
tk.Text
object is used which hasfont
andtabs
attributes.So the easiest solution is to make a
tk.Text
object T, define font and tabs,insert your messages into T then insert T into a
Canvas
window W.Something like this.
这会有所帮助吗?在第12行中,我刚刚添加了
\ t
结果:
Does this will help? In line 12, I just added
\t
Result: