简体   繁体   English

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

[英]Python tkinter to modify only listbox with focus

Good day, 美好的一天,

I have a python application that produces multiple listboxes each with it's own list of data. 我有一个python应用程序,它会产生多个列表框,每个列表框都有自己的数据列表。 These listboxes are created dynamically according to the length of a user generated list. 这些列表框是根据用户生成的列表的长度动态创建的。

I have a button that when clicked i want to trigger some code to effect the active listbox (removing the value from the list amongst other things). 我有一个按钮,当单击该按钮时,我想触发一些代码以影响活动列表框(从列表中删除值等)。

So my plan is to iterate through all the listboxes and only delve deeper if the list box has focus. 因此,我的计划是遍历所有列表框,并且仅在列表框具有焦点时才进行更深入的研究。 But alas, after 2-3 hours of peeling through questions and tkinter documentation I cannot find any way to determine if something has focus or not. 但是可惜,经过2-3个小时的问题解答和tkinter文档,我找不到任何方法来确定某件事是否具有重点。

Thanks in advance! 提前致谢!

Widgets are capable of emitting <FocusIn> and <FocusOut> events, so you can bind callbacks in order to manually keep track of which listbox has focus. 小部件能够发出<FocusIn><FocusOut>事件,因此您可以绑定回调以手动跟踪哪个列表框具有焦点。 Example: 例:

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()

Here, clicking the button will add "another item" to whichever listbox has focus. 在这里,单击按钮会将“另一个项目”添加到具有焦点的任何列表框。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM