我已经读过Why is Button parameter “command” executed when declared?,而Bryan Oakley提供的解决方案看起来很有用,但是就我而言,我需要一些不同的东西(或者我错了)。因为我需要在类MainFrame
中传递参数。
我的代码:
views / login.py
import tkinter as tk
from AgileBooks.controllers.login import submit_login
global_font = 'Helvetica'
global_bg = 'gray25'
global_fg = 'lawn green'
class MainFrame():
# Frame:
frm_login = tk.Tk()
frm_login.title('Login | AgileBooks - Copyright Gonzalo Dambra')
frm_login.geometry('400x300')
frm_login.configure(background=global_bg)
# Labels:
lbl_username = tk.Label(frm_login, text='Username', bg=global_bg, fg=global_fg, font=(global_font, 16))
lbl_username.place(x=150, y=50)
lbl_password = tk.Label(frm_login, text='Password', bg=global_bg, fg=global_fg, font=(global_font, 16))
lbl_password.place(x=150, y=125)
# Inputtexts:
txt_username = tk.Entry(frm_login, font=(global_font, 14))
txt_username.focus()
txt_username.place(x=100, y=80, height=25, width=200)
txt_password = tk.Entry(frm_login, show='*',font=(global_font, 14))
txt_password.place(x=100, y=155, height=25, width=200)
# Button:
btn_login = tk.Button(frm_login, text='Login', font=(global_font, 16), bg=global_bg, fg=global_fg,
command=submit_login(txt_username.get(), txt_password.get()))
btn_login.place(x=165, y=200, height=25)
def main():
frame = MainFrame()
frame.frm_login.mainloop()
if __name__ == '__main__':
main()
controllers / login.py:
def submit_login(username, password):
if len(username) > 0 and len(password) > 0:
print('Username: ', username, ' | Password: ', password)
else:
print('One of the fields is not filled.')
我的问题是方法submit_login
的调用没有任何单击事件,只是在代码运行时才调用它。
我在做什么错了?
答案 0 :(得分:1)
将submit_login
绑定到按钮时,您正在呼叫它:
command=submit_login(txt_username.get(), txt_password.get())
相反,您可以在Tkinter中将命令绑定到lambda:
command=lambda username=txt_username.get(), password=txt_password.get(): submit_login(username, password)
您可能还希望将呼叫移至.get()
,以便在单击时发生:
btn_login = tk.Button(frm_login, text='Login', font=(global_font, 16), bg=global_bg, fg=global_fg,
command=lambda username=txt_username, password=txt_password: submit_login(username, password)
def submit_login(username, password):
username = username.get()
password = password.get()
if len(username) > 0 and len(password) > 0:
print('Username: ', username, ' | Password: ', password)
else:
print('One of the fields is not filled.')