如何在另一个小部件事件处理程序:Tkinter中访问小部件



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

现在我不能使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等中

我能想到的两种解决方案是将textview作为全球化变量,或者将textview传递给command()作为参数。

  • 参数解决方案:
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的多个实例?

最新更新