Python 3.5:打印画布文本

时间:2016-08-13 02:38:38

标签: python tkinter tkinter-canvas

有人可以与我分享如何打印添加到Canvas对象的文本小部件的文本吗?在下面的代码中,我希望系统返回" 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()

1 个答案:

答案 0 :(得分:1)

根据canvas docs

  

您可以通过创建一个在画布C上显示一行或多行文本   文本对象:

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

这将返回画布C上文本对象的对象ID。

现在,你必须修改这样的代码:

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

getting-text-from-canvas

跟进(请参阅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()

enter image description here