【问题标题】:Tkinter - Inserting text into canvas windowsTkinter - 将文本插入画布窗口
【发布时间】:2013-01-03 15:23:19
【问题描述】:

我有一个 Tkinter 画布,其中填充了文本和画布窗口或小部件,使用 create_textcreate_window 方法创建。我放置在画布上的小部件是文本小部件,我想在创建和放置它们之后将文本插入其中。我无法弄清楚如何做到这一点,如果它甚至可能的话。我意识到您可以在创建后使用canvas.itemconfig(tagOrId, cnf) 对其进行编辑,但不能以这种方式插入文本。有解决办法吗?

【问题讨论】:

    标签: python text tkinter tkinter-canvas


    【解决方案1】:

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

    有两种方法可以设置画布文本项的文本。可以使用itemconfigure设置text属性,也可以使用画布的insert方法在文本项中插入文本。

    在以下示例中,文本项将显示字符串“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()
    

    【讨论】:

      猜你喜欢
      • 2017-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-10
      • 1970-01-01
      • 2012-05-11
      • 2023-03-21
      • 1970-01-01
      相关资源
      最近更新 更多