Could anyone share with me how to print the text of the text widget added to a Canvas object? In the code below, I want the system return the value of "hello" when mouse on the text, however, it turns out giving me "1". Don't know why. Could anyone help me?
Many many thanks!!!
import tkinter
from tkinter import *def show_text(event):print (canvas.text)master = tkinter.Tk()
canvas = tkinter.Canvas(master, width = 200, height = 100)
canvas.pack()
canvas.bind('<Enter>',show_text)
canvas.text = canvas.create_text(20, 30, text="hello")mainloop()
According to the canvas docs:
You can display one or more lines of text on a canvas C by creating atext object:
id = C.create_text(x, y, option, ...)
This returns the object ID of the text object on canvas C.
Now, you gotta modify the code something like this:
import tkinter
from tkinter import *def show_text(event):print (canvas.itemcget(obj_id, 'text'))master = tkinter.Tk()
canvas = tkinter.Canvas(master, width = 200, height = 100)
canvas.pack()
canvas.bind('<Enter>',show_text)
obj_id = canvas.create_text(20, 30, text="hello")mainloop()
Follow up (see the documentation for Label.config:
import tkinter
from tkinter import *
from tkinter import ttkdef show_text(event):print (canvas.itemcget(canvas.text, 'text'))#The command of writing text 'hello' in sch_Label to replace the text 'the info shows here'sch_Label.config(text = 'hello!')master = tkinter.Tk()
canvas = tkinter.Canvas(master, width = 200, height = 100)
canvas.pack()
canvas.bind('<Enter>',show_text)
canvas.text = canvas.create_text(20, 30, text="hello")pad1 = ttk.Notebook(master)
pad1.pack(side=RIGHT, expand=1, fill="both")
tab1 = Frame(pad1)
pad1.add(tab1, text = "Schedule")
pad1.pack(side=RIGHT)
sch_Label = ttk.Label(tab1, text='The info shows here')
sch_Label.pack(side="top", anchor="w")
mainloop()