问题描述
我有一个 Tkinter 画布,其中填充了使用 create_text
和 create_window
方法创建的文本和画布窗口或小部件.我放置在画布上的小部件是文本小部件,我想在创建和放置它们后将文本插入其中.如果可能的话,我无法弄清楚如何做到这一点.我意识到您可以在使用 canvas.itemconfig(tagOrId, cnf)
创建后编辑它们,但不能以这种方式插入文本.有没有办法解决这个问题?
I have a Tkinter canvas populated with text and canvas windows, or widgets, created using the create_text
and create_window
methods. The widgets I place on the canvas are text widgets, and I want to insert text into them after they are created and placed. I can't figure out how to do this, if it's even possible. I realise you can edit them after creation using canvas.itemconfig(tagOrId, cnf)
, but text can't be inserted that way. Is there a solution to this?
推荐答案
首先,让我们弄清楚术语:您不是在创建小部件,而是在创建画布项目.Tkinter 文本小部件和画布文本项之间存在很大差异.
First, lets get the terminology straight: you aren't creating widgets, you're creating canvas items. There's a big difference between a Tkinter text widget and a canvas text item.
有两种方法可以设置画布文本项的文本.您可以使用 itemconfigure 来设置 textcode> 属性,您可以使用 insert 方法用于在文本项中插入文本的画布.
There are two ways to set the text of a canvas text item. You can use itemconfigure to set the text
attribute, and you can use the insert method of the canvas to insert text in the text item.
在以下示例中,文本项将显示字符串这是新文本":
In the following example, the text item will show the string "this is the new text":
import Tkinter as tk
class Example(tk.Frame):
def __init__(self, *args, **kwargs):
tk.Frame.__init__(self, *args, **kwargs)
canvas = tk.Canvas(self, width=800, height=500)
canvas.pack(side="top", fill="both", expand=True)
canvas_id = canvas.create_text(10, 10, anchor="nw")
canvas.itemconfig(canvas_id, text="this is the text")
canvas.insert(canvas_id, 12, "new ")
if __name__ == "__main__":
root = tk.Tk()
Example(root).pack(side="top", fill="both", expand=True)
root.mainloop()
这篇关于Tkinter - 将文本插入画布窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!