python - 如何在另一个小部件事件处理程序中访问小部件:Tkinter
问题描述
我正在 tkinter 中创建一个 GUI,在单击按钮后出现的子窗口中有一个listbox
和一个项目。正在显示 a 的值,这些值基本上是磁盘映像中文件/目录的名称。我想更改事件上小部件的文本并显示所选文件的类型或路径。Text
Listbox
dict
Text
<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 等中。
解决方案
我能想到的两个解决方案是创建一个全球化变量或作为参数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 实例?
推荐阅读
- python - 如何获得熊猫条形图的颜色
- pyspark - 在火花中创建表需要很多时间
- numpy - sparkSQL 过滤器功能不适用于 NaN
- c# - 设置 Response.Cookies[ASP.NET_SessionId].Secure = true; 在代码中清除我的 HttpContext.Current.Session["anyData"]
- c++ - 如何使用 OpenMP 并行化嵌套的 for 循环
- java - 如何用逗号分隔递归字符串
- python - 断言 self.selection 不是无,“字段 %s 没有选择”% self
- flutter - Flutter:如何等待异步功能完成?
- json - 我应该在 GET 响应中返回对象 ID 还是整个对象实体?
- eclipse - eclipse 在运行 .jsp 文件时停止响应