Python 3.5:打印Canvas 文本

Python 3.5: Print Canvas Text

任何人都可以与我分享如何打印添加到 Canvas 对象的文本小部件的文本吗?在下面的代码中,当鼠标悬停在文本上时,我希望系统 return 得到 "hello" 的值,但是结果却给了我“1”。不知道为什么。谁能帮帮我?

非常非常感谢!!!

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()

根据 canvas docs:

You can display one or more lines of text on a canvas C by creating a text object:

id = C.create_text(x, y, option, ...)

This returns the object ID of the text object on canvas C.

现在,您必须像这样修改代码:

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()

跟进(见Label.config的文档:

import tkinter
from tkinter import *
from tkinter import ttk

def 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()