Python Tkinter - 将文本插入画布窗口

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14423959/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:27:41  来源:igfitidea点击:

Tkinter - Inserting text into canvas windows

pythontexttkintertkinter-canvas

提问by Yngve

I have a Tkinter canvas populated with text and canvas windows, or widgets, created using the create_textand create_windowmethods. 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 画布,其中填充了使用create_textcreate_window方法创建的文本和画布窗口或小部件。我放置在画布上的小部件是文本小部件,我想在创建和放置它们后将文本插入其中。如果可能的话,我无法弄清楚如何做到这一点。我意识到您可以在创建后使用 编辑它们canvas.itemconfig(tagOrId, cnf),但不能以这种方式插入文本。这个问题有方法解决吗?

采纳答案by Bryan Oakley

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.

首先,让我们明白术语:您不是在创建小部件,而是在创建画布项目。Tkinter 文本小部件和画布文本项之间存在很大差异。

There are two ways to set the text of a canvas text item. You can use itemconfigureto set the textattribute, and you can use the insertmethod of the canvas to insert text in the text item.

有两种方法可以设置画布文本项的文本。可以使用itemconfigure设置text属性,也可以使用canvas的insert方法在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()