Python Tkinter类中按钮绑定回车键失效问题求助
Tkinter按钮绑定回车键无效问题解决
问题描述
刚学习Tkinter,尝试为按钮绑定回车键(Enter)但始终无法生效:
- 直接绑定按钮:
Enter.bind('<Return>', lambda:self.retrieve_Input(t)) - 绑定到自身:
self.bind('<Return>', lambda:self.retrieve_Input(t))
只有移除lambda才能触发,但不符合需求。以下是完整代码:
import sys import tkinter as tk from tkinter import ttk class windows(tk.Tk): def __init__(self, *args, **kwargs): tk.Tk.__init__(self, *args, **kwargs) self.wm_title("Test Application") self.lift() #Bringing the GUI to the front of the screen main_frame = tk.Frame(self, height=400, width=600) #Creating a main Frame for all pages main_frame.pack(side="top", fill="both", expand=True) main_frame.grid_rowconfigure(0, weight=1) #Configuring the location of the main frame using grid main_frame.grid_columnconfigure(0, weight=1) # We will now create a dictionary of frames self.frames = {} for F in (MainPage, CompletionScreen): #Add the page components to the dictionary. page = F(main_frame, self) self.frames[F] = page #The windows class acts as the root window for the frames. page.grid(row=0, column=0, sticky="nsew") self.show_page(MainPage) #Method to switch Pages def show_page(self, cont): frame = self.frames[cont] frame.tkraise() ########################################################################## class MainPage(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) tk.Label(self, text="Project Python Search Engine", bg='white').pack() tk.Label(self, text="", bg='white').pack() tk.Label(self, text="Song", bg='white').pack() tk.Label(self, text="", bg='white').pack() t = tk.Entry(self, bg='white', width = 50) t.pack() tk.Label(self, text="", bg='white').pack() Enter = tk.Button(self, text='Search', command= lambda:self.retrieve_Input(t)) Enter.pack() tk.Button(self, text="Latest Popular Songs", command=lambda:self.Popular_Songs(t)).pack() #Line 210 onwards Enter.bind('<Return>', lambda:self.retrieve_Input(t)) def retrieve_Input(self, t): print ("work") print (t) class CompletionScreen(tk.Frame): def __init__(self, parent, controller): tk.Frame.__init__(self, parent) label = tk.Label(self, text="Completion Screen, we did it!") label.pack(padx=10, pady=10) switch_window_button = ttk.Button( self, text="Return to menu", command=lambda: controller.show_page(MainPage) ) switch_window_button.pack(side="bottom", fill=tk.X) if __name__ == "__main__": App = windows() App.mainloop()
问题原因及解决方法
- 原因:按钮未获得键盘焦点,只有控件获得焦点时,绑定在该控件上的键盘事件才会触发。用户输入内容时,焦点通常在输入框(Entry)上,而非按钮,因此绑定在按钮上的回车键事件无法触发。
- 解决方法:将回车键绑定设置在输入框(Entry)上,因为输入框是用户交互时默认获得焦点的控件。同时注意,键盘事件的回调函数默认会接收一个
event参数,lambda需要包含该参数避免报错。
修改MainPage类中的绑定代码,将原来绑定按钮的语句替换为:
t.bind('<Return>', lambda event: self.retrieve_Input(t))
内容的提问来源于stack exchange,提问作者Dylan Thomas
相关产品推荐
相关产品推荐

