是否有办法从一个输入字段跳转到另一个输入字段?



我试图在python中制作具有多个条目的计费软件,因此很难使用鼠标从一个输入字段移动到另一个输入字段,我只是希望它从客户姓名字段跳到客户电话,当我按下"enter"时没有提交条目;键,但是不工作,我怎么才能使它工作


from Tkinter import*
root = Tk()
root.geometry('1350x700+0+0')
root.resizable(width=False,height=False)
root.title('Billing App')
def jump_cursor(event):
customer_PhoneNo_entry.icursor(0)
customer_detail_frame=Frame(root,bd=10,highlightbackground="blue", highlightthickness=2)
customer_detail_frame.place(x=0,y=10,width=1350,height=100)
customer_detail_lbl=Label(customer_detail_frame,text="customer detail",font=('verdana',10,'bold'))
customer_detail_lbl.grid(row=0,column=0,pady=10,padx=20)
customer_name_lbl=Label(customer_detail_frame,text="customer name",font=('verdana',10,'bold'))
customer_name_lbl.grid(row=1,column=0,pady=10,padx=20)
customer_name_entry=Entry(customer_detail_frame,width=20,textvariable = Customer_Name)
customer_name_entry.grid(row=1,column=1,pady=10,padx=20)
customer_phoneno_lbl=Label(customer_detail_frame,text="phone no.",font=('verdana',10,'bold'))
customer_phoneno_lbl.grid(row=1,column=2,pady=10,padx=20)
customer_PhoneNo_entry=Entry(customer_detail_frame,width=20,textvariable = Customer_Ph_No)
customer_PhoneNo_entry.grid(row=1,column=3,pady=10,padx=20)
customer_PhoneNo_entry.bind("<Return>",jump_cursor)

这个答案帮助我解决了同样的问题。


  • 首先,得到customer_detail_frame的所有子代即Entry,使用winfo_children()

  • 第二,将每个子节点绑定到<Return>,其中可以使用lambda创建另一个函数)。

  • 最后,定义jump_cursor函数,这样它就可以切换关注所需的小部件,使用focus_set()

下面是你的代码修改后的样子:

from tkinter import*
root = Tk()
root.geometry('1350x700+0+0')
root.resizable(width=False,height=False)
root.title('Billing App')
Customer_Name, Customer_Ph_No = StringVar(), StringVar()
customer_detail_frame=Frame(root,bd=10,highlightbackground="blue", highlightthickness=2)
customer_detail_frame.place(x=0,y=10,width=1350,height=100)
customer_detail_lbl=Label(customer_detail_frame,text="customer detail",font=('verdana',10,'bold'))
customer_detail_lbl.grid(row=0,column=0,pady=10,padx=20)
customer_name_lbl=Label(customer_detail_frame,text="customer name",font=('verdana',10,'bold'))
customer_name_lbl.grid(row=1,column=0,pady=10,padx=20)
customer_name_entry=Entry(customer_detail_frame,width=20,textvariable = Customer_Name)
customer_name_entry.grid(row=1,column=1,pady=10,padx=20)
customer_phoneno_lbl=Label(customer_detail_frame,text="phone no.",font=('verdana',10,'bold'))
customer_phoneno_lbl.grid(row=1,column=2,pady=10,padx=20)
customer_PhoneNo_entry=Entry(customer_detail_frame,width=20,textvariable = Customer_Ph_No)
customer_PhoneNo_entry.grid(row=1,column=3,pady=10,padx=20)

def jump_cursor(event, entry_list, this_index):
next_index = (this_index + 1) % len(entry_list)
entry_list[next_index].focus_set()
entries = [child for child in customer_detail_frame.winfo_children() if isinstance(child, Entry)]
for idx, entry in enumerate(entries):
entry.bind('<Return>', lambda e, idx=idx: jump_cursor(e, entries, idx))

root.mainloop()

最新更新