【发布时间】:2020-12-31 03:48:47
【问题描述】:
from tkinter import *
from tkinter.ttk import *
root = Tk()
listbox = None
listboxMultiple = None
listboxStr = None
listboxMultipleStr = None
def main():
global root
global listboxStr
global listboxMultipleStr
global listbox
global listboxMultiple
root.protocol("WM_DELETE_WINDOW", exitApplication)
root.title("Title Name")
root.option_add('*tearOff', False) # don't allow tear-off menus
root.geometry('1600x300')
listboxStr = StringVar()
listboxStr.set("ABCD")
listbox = Listbox(root, name="lb1", listvariable=listboxStr, width=120)
listbox.pack(side=LEFT)
listbox.bind("<<ListboxSelect>>", selectListItemCallback)
listboxMultipleStr = StringVar()
listboxMultipleStr.set("")
listboxMultiple = Listbox(root, name="lb2", listvariable=listboxMultipleStr, width=120)
listboxMultiple.pack(side=LEFT)
root.mainloop()
def selectListItemCallback(event):
global listboxMultipleStr
global listbox
global listboxMultiple
print("event.widget is {} and listbox is {} and listboxMultiple is {}\n".format(event.widget, listbox, listboxMultiple))
selection = event.widget.curselection()
listboxMultipleStr.set("")
if selection:
index = selection[0]
data = event.widget.get(index)
newvalue = "{}\n{}".format(data,"SOMETHING")
print("selected \"{}\"\n".format( data ))
print("newvalue is \"{}\"\n".format( newvalue ))
listboxMultiple.insert(END, "{}".format(data))
listboxMultiple.insert(END, "SOMETHING")
#listboxMultipleStr.set( newvalue )
else:
pass
def exitApplication():
global root
root.destroy()
if __name__ == "__main__":
main()
在 Windows 7 上使用 python3。我为我的两个列表框小部件之一设置了回调“selectListItemCallback”。然而,当我单击“lb1”中的文本时,它按预期工作,我用相同的选定文本更新“lb2”,并在“lb2”中添加另一行。
问题是,当我然后选择“lb2”中的项目时,它仍然调用回调并且 event.widget 是“lb1”而不是“lb2”。
我的意图是在“lb1”中有一个项目列表,当我选择其中任何一个时,“lb2”会填充与所选“lb1”项目相关的信息。而且,我不希望在我的“lb2”小部件中调用选择回调。
你能看出我做错了什么导致这种奇怪的行为吗?
谢谢。
我已经发布了代码;这确实在我使用 python3 的 Windows 7 机器上运行。确切地说是 Python 3.8.6。
【问题讨论】: