【发布时间】:2021-07-29 10:00:33
【问题描述】:
所以,我一直在尝试将回车键绑定到按下我在这个 python 程序中的按钮——是的,我已经看到了许多与此相关的其他问题,但是他们的代码都没有与这个程序一起使用不管什么原因。在下面发布代码,看看是否有人有好的解决方案。
下面的代码按预期完成所有事情——它会拉出 GUI,显示愚蠢的 jar-jar 图片、按钮和带有预填充文本的输入字段,但我键盘上的 enter 键不会产生结果就像我用鼠标按下按钮时发生的那样。
import tkinter as tk
from PIL import Image, ImageTk, ImageTransform
from tkinter.filedialog import askopenfile
root = tk.Tk()
class guiMenu:
def __init__(self, master):
myFrame = tk.Frame(master)
# logo
logo = Image.open('jar.jpg')
logo2 = logo.resize((200, 200), Image.ANTIALIAS)
logo2 = ImageTk.PhotoImage(logo2)
self.logo_label = tk.Label(image=logo2)
self.logo_label.image = logo2
self.logo_label.grid(column=1, row=0)
# instructions
self.instructions = tk.Label(master,
text="Input your email address and password to extract email attachments.\n "
"You should also select the folder you wish the attachments to reach.")
self.instructions.grid(columnspan=3, column=0, row=3)
# store the user login info in variables
def storeUserLogin():
clientEmailInput = self.emailEntry.get()
clientPasswordInput = self.passwordEntry.get()
print(clientEmailInput, clientPasswordInput)
# delete email prefill on click
def onEmailClick(event):
self.emailEntry.configure()
self.emailEntry.delete(0, 100) # this deletes the preexisting text for email entry
self.emailEntry.unbind('<Button-1>', self.on_click_id)
# delete pw prefill on click
def onPWClick(event):
self.passwordEntry.configure()
self.passwordEntry.delete(0, 100) # this deletes the preexisting text for email entry
self.passwordEntry.unbind('<Button-1>', self.on_click_id2)
# email entry box
self.emailEntry = tk.Entry(master, width=50)
# emailEntry = tk.StringVar(None)
# emailEntry.set("Email Address")
self.emailEntry = tk.Entry()
self.emailEntry.insert(0, "Email Address")
self.emailEntry.configure()
self.emailEntry.grid(column=1, row=1)
# on-click function
self.on_click_id = self.emailEntry.bind('<Button-1>', onEmailClick)
# enter key function
def enterFunction(event=None):
master.bind('<Return>', lambda event=None, loginButton.invoke())
# password entry box
self.passwordEntry = tk.Entry()
self.passwordEntry.insert(0, "Password")
self.passwordEntry.grid(column=1, row=2)
# on click function
self.on_click_id2 = self.passwordEntry.bind('<Button-1>', onPWClick)
# button to login
def loginButton():
self.loginButtonText = tk.StringVar()
self.loginButton = tk.Button(master, textvariable=self.loginButtonText, font="Arial",
commands=lambda: [storeUserLogin(), enterFunction()],
width=5, height=2,
bg="white", fg="black")
self.loginButtonText.set("LOGIN")
self.loginButton.grid(column=1, row=4)
self.canvas = tk.Canvas(root, width=600, height=250)
self.canvas.grid(columnspan=3)
g = guiMenu(root)
root.mainloop()
【问题讨论】:
-
绑定代码在
enterFunction()中,您的代码中永远不会调用它。
标签: python user-interface tkinter button