这似乎是一个相当简单的问题,但我无法解决它。运行以下代码时,第一个窗口带有两个输入框。当我们使用'TAB'键时,第二个输入框将弹出一个窗口,需要从ListBox中选择一个值。我编写了ListBox中的值需要进入第一个窗口的输入框的部分,但是,一旦做出选择,我无法让第二个窗口关闭。
from Tkinter import *
def fn_jump(event=None):
def listbox_update(data):
# delete previous data
listbox.delete(0, 'end')
# put new data
for item in data:
listbox.insert('end', item)
def on_select(event):
# display element selected on list
print('(event) previous:', event.widget.get('active'))
print('(event) current:', event.widget.get(event.widget.curselection()))
a = (event.widget.get(event.widget.curselection()))
print a
txtbox2.delete(0, END)
txtbox2.insert(0,a)
#listbox.bind('<<Return>>', window3.quit()) #This is not working
window3 = Toplevel()
window3.title("This window popped out")
window3.geometry('{}x{}'.format(500,200))
listbox = Listbox(window3, width=60)
listbox.grid(row=0)
listbox.bind('<<ListboxSelect>>', on_select)
test_list = ('apple', 'banana', 'Cranberry', 'dogwood', 'alpha', 'Acorn', 'Anise', 'Strawberry')
listbox_update(test_list)
root = Tk()
txtbox1 = Entry(root)
txtbox2 = Entry(root)
txtbox1.grid(row=0)
txtbox2.grid(row=1)
txtbox2.bind('<KeyRelease>', fn_jump)
root.mainloop()
更换:
#listbox.bind('<<Return>>', window3.quit()) #This is not working
有:
listbox.bind('<Return>', lambda event : window3.destroy())
正如您在txtbox2.bind('<KeyRelease>', fn_jump)
中所看到的那样,bind
期望使用对回调函数的引用。按下输入的正确的绑定类型是'<Return>'
而不是'<<Return>>'
。
在该场景中,由于函数是在函数内定义的,因此只是破坏窗口意味着程序仍然在父函数fn_jump内,从而一遍又一遍地弹出第二个窗口。为了克服这个问题,我强烈地将焦点设置在根窗口上的一个文本框中,以解决问题(我认为会有一个我们可以使用的exit(),但我对Python来说相对较新)。
这是最终的工作代码:
from Tkinter import *
def fn_jump(event=None):
def listbox_update(data):
# delete previous data
listbox.delete(0, 'end')
# put new data
for item in data:
listbox.insert('end', item)
def on_select(event):
# display element selected on list
print('(event) previous:', event.widget.get('active'))
print('(event) current:', event.widget.get(event.widget.curselection()))
a = (event.widget.get(event.widget.curselection()))
print a
txtbox2.delete(0, END)
txtbox2.insert(0,a)
window3 = Toplevel()
window3.title("This window popped out")
window3.geometry('{}x{}'.format(500,200))
listbox = Listbox(window3, width=60)
listbox.grid(row=0)
listbox.focus_set()
listbox.bind('<<ListboxSelect>>', on_select)
listbox.bind('<Return>', lambda event: window3.destroy()) #This is a fix
txtbox1.focus_set() #This is a fix
test_list = ('apple', 'banana', 'Cranberry', 'dogwood', 'alpha', 'Acorn', 'Anise', 'Strawberry')
listbox_update(test_list)
root = Tk()
txtbox1 = Entry(root)
txtbox2 = Entry(root)
txtbox1.grid(row=0)
txtbox2.grid(row=1)
txtbox2.bind('<KeyRelease>', fn_jump)
root.mainloop()