【问题标题】:Need help Dynamically resizing my text to fit in the tkinter canvas需要帮助动态调整我的文本大小以适合 tkinter 画布
【发布时间】:2021-04-11 09:25:59
【问题描述】:

当我遇到这个问题时,我最近正在编写一个小型 Python 脚本。我试图创建一个条形的画布并将文本写入其中,期望文本会自动调整到画布的边界(类似于文本框在文字处理软件中的工作方式)。但是文本显然超出了界限。

屏幕截图

代码

from tkinter import *
top = Tk()  
top.geometry("130x370")
c = Canvas(top,bg = "pink",height = "370")
c.create_text(30,30,fill="darkblue",font="Times 20 italic bold",text="Hey There!")
c.pack()
top.mainloop() 

【问题讨论】:

  • 你真的需要使用Canvas吗? Text 小部件自动换行。
  • 澄清一下:您实际上并不想resize 文本(更改字体大小)而是wrap 文本,对吗?如果有的话,您不使用文本字段的原因是什么?如果画布完全“满”(垂直),它应该如何表现?
  • 好吧,我不确定文本字段是否能正确完成这项工作,如果画布垂直填满,则应调整整个文本的大小以适合画布。只需将其视为将文本作为输入并打印到自定义大小的图像上的应用程序。

标签: python tkinter canvas


【解决方案1】:

首先,Canvas.create_text() 方法有一个 width 选项,它设置文本的最大宽度,超出该宽度。为了在调整窗口大小时获得动态效果,可以在绑定到<Configure> 事件的函数中更改此width 选项(下例中的resize() 函数)。

其次,为了检查文本是否垂直适合画布,我使用Canvas.bbox(item_id) 方法来获取文本边界框的坐标。然后,只要文本底部低于画布底部,我就会减小字体大小。

示例如下:

import tkinter as tk
top = tk.Tk()
top.geometry("130x370")

def resize(event):
    font = "Times %i italic bold"
    fontsize = 20
    x0 = c.bbox(text_id)[0] # x-coordinate of the left side of the text
    c.itemconfigure(text_id, width=c.winfo_width() - x0, font=font % fontsize)
    # shrink to fit
    height = c.winfo_height() # canvas height
    y1 = c.bbox(text_id)[3] # y-coordinate of the bottom of the text
    while y1 > height and fontsize > 1:
        fontsize -= 1
        c.itemconfigure(text_id, font=font % fontsize)
        y1 = c.bbox(text_id)[3]

c = tk.Canvas(top, bg="pink", height="370")
text_id = c.create_text(30, 30, anchor="nw", fill="darkblue", font="Times 20 italic bold", text="Hey There!")
c.pack(fill="both", expand=True)
c.bind("<Configure>", resize)

top.mainloop()

还要注意,我在.create_text() 中将文本的锚点设置为西北方向,这样 (30, 30) 是文本左上角的坐标而不是中心的坐标,以确保文字可见。

【讨论】:

    猜你喜欢
    • 2020-09-24
    • 2014-05-15
    • 1970-01-01
    • 2018-07-11
    • 2011-09-03
    • 2020-10-13
    • 2014-01-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多