在tkinter中编辑文本

时间:2013-03-04 01:49:34

标签: python text tkinter

所以我把create_text变量传递给了“text1”

text1 = UseCanvas(self.window, "text", width = 100, height = 100, text = "Goodbye")

使用:

self.create_text(20,25 width=100,  anchor="center", text =self.text, tags= self.tag1)

将它传递给另一个班级后。

如何编辑该文本小部件?我希望它说“你好”而不是“再见”。我看了一遍,除了改变文字,我可以做任何我想做的事。

1 个答案:

答案 0 :(得分:3)

您应该使用画布的itemconfig方法来修改文本属性。你必须给它一个或多个画布项的id。这是一个小工作示例,可让您更改一个文本对象的文本:

# use 'tkinter' instead of 'Tkinter' if using python 3.x
import Tkinter as tk 

class Example(tk.Frame):
    def __init__(self, *args, **kwargs):
        tk.Frame.__init__(self, *args, **kwargs)

        self.button = tk.Button(self, text="Change text", command=self.on_change_text)
        self.canvas = tk.Canvas(self, width=400, height=400)

        self.button.pack(side="top", anchor="w")
        self.canvas.pack(side="top", fill="both", expand=True)

        # every canvas object gets a unique id, which can be used later
        # to change the object. 
        self.text_id = self.canvas.create_text(10,10, anchor="nw", text="Hello, world")

    def on_change_text(self):
        self.canvas.itemconfig(self.text_id, text="Goodbye, world")

if __name__ == "__main__":
    root = tk.Tk()
    view = Example(root)
    view.pack(side="top", fill="both", expand=True)
    root.mainloop()