[英]Tkinter: How to set relwidth of a Text widget in a Canvas?
In Tkinter, when you place a Text widget in the main window, you can set the relation between the Text widget's width and the main window's width: 在Tkinter中,将“文本”小部件放置在主窗口中时,可以设置“文本”小部件的宽度和主窗口的宽度之间的关系:
text.place(x = 10, y = 10, relwidth = 0.5)
Is it posible to do the same if the Text widget's parent window is a Canvas widget? 如果“文本”窗口小部件的父窗口是“画布”窗口小部件,是否可以执行相同的操作? I tried to use the Canvas itemconfig()
method, but it doesn't work: 我尝试使用Canvas itemconfig()
方法,但是它不起作用:
text = Text(canvas)
canvas.create_window(10, 10, anchor = NW, window = text)
canvas.itemconfig(text, relwidth = 0.5)
Thanks in advance for your help. 在此先感谢您的帮助。
No, explicitly setting a relative width is only available when using place
. 不,仅在使用place
时显式设置相对宽度才可用。 If you are creating an object on a canvas, it is up to you to do the math to configure the width of the object. 如果要在画布上创建对象,则要由数学来配置对象的宽度。
It's fairly simple to recompute the width of a text widget by binding to the <Configure>
event of the canvas, since that event fires whenever the canvas changes size (among other reasons). 通过绑定到画布的<Configure>
事件来重新计算文本小部件的宽度非常简单,因为只要画布更改大小(其他原因),该事件就会触发。
Here's an example that places a text widget on a canvas, and keeps its width at half the width of the canvas. 这是一个将文本小部件放置在画布上并将其宽度保持为画布宽度一半的示例。 Run the code, and notice that as you resize the window, the text widget is kept at 50% of the width of the canvas. 运行代码,并注意在调整窗口大小时,文本小部件将保持为画布宽度的50%。
import tkinter as tk
class Example():
def __init__(self):
self.root = tk.Tk()
self.canvas = tk.Canvas(self.root, background="bisque")
self.canvas.pack(fill="both", expand=True)
self.text = tk.Text(self.canvas)
print("feh:", str(self.text))
self.canvas.create_window(10, 10, anchor="nw", window=self.text, tags=("text",))
self.canvas.bind("<Configure>", self._canvas_resize)
def _canvas_resize(self, event):
relwidth = event.width / 2
self.canvas.itemconfigure("text", width=relwidth)
e = Example()
tk.mainloop()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.