【问题标题】:Python 3.5: Print Canvas TextPython 3.5:打印画布文本
【发布时间】:2016-08-13 02:38:38
【问题描述】:

谁能与我分享如何打印添加到 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()

【问题讨论】:

    标签: python tkinter tkinter-canvas


    【解决方案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()
    

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

    【讨论】:

    • 非常感谢,这正是我想要的。我可以对此提出后续问题吗?除了打印 hello 之外,我还想在鼠标打开时将世界“hello”写入笔记本小部件中的选项卡标签。但是,除了事件的小部件之外,我找不到引用特定对象的方法。你有什么主意吗?我根据您的版本附上如下代码。非常感谢。你知道,我一直在编写 VB 和 Python 新手,所以真的不知道它的对象引用系统是如何工作的。您的建议将节省我很多时间!
    • import tkinter from tkinter import * def show_text(event): print (canvas.itemcget(canvas.text, 'text')) #sch_Label中写入文字'hello'替换文字的命令'这里显示的信息' master = tkinter.Tk() canvas = tkinter.Canvas(master, width = 200, height = 100) canvas.pack() canvas.bind('',show_text) canvas.text = canvas.create_text(20, 30, text="hello")
    • pad1 = ttk.Notebook(master) pad1.pack(side=RIGHT, expand=1, fill="both") tab1 = ttk.Frame(pad1) pad1.add(tab1, text = "Schedule") pad1.pack(side=RIGHT) sch_Label = ttk.Label(tab1, text='这里显示的信息') sch_Label.pack(side="top", anchor="w") mainloop()跨度>
    猜你喜欢
    • 2011-07-10
    • 2013-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-09-30
    • 2015-02-10
    相关资源
    最近更新 更多