gpt4 book ai didi

Python tkinter 仅修改具有焦点的列表框

转载 作者:太空宇宙 更新时间:2023-11-04 01:13:17 26 4
gpt4 key购买 nike

你好,

我有一个 python 应用程序,它生成多个列表框,每个列表框都有自己的数据列表。这些列表框是根据用户生成的列表的长度动态创建的。

我有一个按钮,当我点击它时我想触发一些代码来影响事件列表框(除其他外从列表中删除值)。

所以我的计划是遍历所有列表框,只有在列表框有焦点时才深入研究。但遗憾的是,在浏览了 2-3 个小时的问题和 tkinter 文档之后,我找不到任何方法来确定某件事是否有焦点。

提前致谢!

最佳答案

小部件能够发出 <FocusIn><FocusOut>事件,因此您可以绑定(bind)回调以手动跟踪哪个列表框具有焦点。示例:

from Tkinter import *

class App(Tk):
def __init__(self, *args, **kargs):
Tk.__init__(self, *args, **kargs)
self.focused_box = None
for i in range(4):
box = Listbox(self)
box.pack()
box.insert(END, "box item #1")
box.bind("<FocusIn>", self.box_focused)
box.bind("<FocusOut>", self.box_unfocused)

button = Button(text="add item to list", command=self.add_clicked)
button.pack()

#called when a listbox gains focus
def box_focused(self, event):
self.focused_box = event.widget

#called when a listbox loses focus
def box_unfocused(self, event):
self.focused_box = None

#called when the user clicks the "add item to list" button
def add_clicked(self):
if not self.focused_box: return
self.focused_box.insert(END, "another item")

App().mainloop()

在这里,单击按钮会将“另一个项目”添加到具有焦点的列表框中。

关于Python tkinter 仅修改具有焦点的列表框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26365546/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com