首页 > 解决方案 > 如何在另一个小部件事件处理程序中访问小部件:Tkinter

问题描述

我正在 tkinter 中创建一个 GUI,在单击按钮后出现的子窗口中有一个listbox和一个项目。正在显示 a 的值,这些值基本上是磁盘映像中文件/目录的名称。我想更改事件上小部件的文本并显示所选文件的类型或路径。TextListboxdictText<ListboxSelect>

现在我不能Text全局化,因为它必须出现在子窗口上,所以我需要一种在Listbox. 我可以给处理程序参考Textbox吗?

这是我的代码;

def command(event):
    ...          #Need to change the Text here, how to access it?

def display_info(dict,filename):
    child_w = Tk()
    listbox = Listbox(child_w)
    textview = Text(child_w)

    ...

    listbox.bind(<ListboxSelect>,command)

def upload_file():



window = Tk()
upl_button = Button(command=upload_file)

window.mainloop()
    

有没有办法将文本视图创建为全局,然后稍后更改其属性以显示在 child_window 等中。

标签: pythontkinterreferenceglobal-variables

解决方案


我能想到的两个解决方案是创建一个全球化变量或作为参数textview传递。textviewcommand()

  • 参数解法:
def command(event,txtbox):
    txtbox.delete(...)

def display_info(dict,filename):
    child_w = Tk()
    listbox = Listbox(child_w)
    textview = Text(child_w)

    ...

    listbox.bind('<ListboxSelect>',lambda event: command(event,textview))
  • 或者只是将其全球化:
def command(event):
    textview.delete(...)

def display_info(dict,filename):
    global textview

    child_w = Tk()
    listbox = Listbox(child_w)
    textview = Text(child_w)

    ...

    listbox.bind('<ListboxSelect>',command)

虽然说了这么多,但最好记住创建多个实例Tk几乎从来都不是一个好主意。阅读:为什么不鼓励使用多个 Tk 实例?


推荐阅读