Tkinter按钮不执行操作

时间:2017-01-08 04:11:06

标签: python tkinter

完全披露,我是一个Python新手,甚至比Tkinter更新。我有以下代码,我可以从各种来源解析,显示按钮和对话框,因为我希望它们显示。 “取消”按钮工作正常,但是当我输入正确的凭据并单击“确定”时,没有任何反应。根据我所读到的内容,我认为我可能有绑定和/或回调问题,但我不确定。经过几个小时的阅读和观看YouTube视频后,我正在敲打桌子。任何帮助将不胜感激。

from Tkinter import *
    master = Tk()

    def login_info():
        bankUsername = bank_user.get()
        bankPassword = bank_pass.get()
        return

    Label(master, text=str(properBankName) + " Username: ").grid(row=0, sticky = "E")
    Label(master, text="Password: ").grid(row=1, sticky = "E")

    master.title("Please Enter Credentials")

    bank_user = Entry(master)
    bank_pass = Entry(master)

    bank_user.grid(row=0, column=1)
    bank_pass.grid(row=1, column=1)

    Button(master, height=1, width=8, text='OK', command=login_info).grid(row=3, column=0, sticky = "E", pady=4)
    Button(master, height=1, width=8, text='Cancel', command=master.quit).grid(row=3, column=1, sticky = "W", pady=4)

    master.mainloop()

1 个答案:

答案 0 :(得分:1)

我使用全局变量来保存值,然后使用master.destroy()来关闭窗口 (在Linux上master.quit()不会执行关闭窗口的master.destroy()

我使用变量login来识别单击了哪个按钮。

我对columnspan=2使用Entry并向右移动Buttons一个单元格 - 现在它看起来更好。

顺便说一句:行Button(...).grid(...)非常长,所以我把它们分成两行,以便更具可读性。

代码:

from Tkinter import *

# --- functions ---

def login_info():
    # inform function to use external/global variables
    global bankUsername
    global bankPassword
    global login

    login = True

    bankUsername = bank_user.get()
    bankPassword = bank_pass.get()

    # quit window 
    master.destroy()

# --- main ---

# create global variables
bankUsername = None
bankPassword = None
login = False

# - GUI

master = Tk()

Label(master, text="Username:").grid(row=0, sticky="E")
Label(master, text="Password:").grid(row=1, sticky="E")

master.title("Please Enter Credentials")

bank_user = Entry(master)
bank_pass = Entry(master)

bank_user.grid(row=0, column=1, columnspan=2)
bank_pass.grid(row=1, column=1, columnspan=2)

b = Button(master, height=1, width=8, text='OK', command=login_info)
b.grid(row=3, column=1, sticky="E", pady=4)

b = Button(master, height=1, width=8, text='Cancel', command=master.destroy)
b.grid(row=3, column=2, sticky="W", pady=4)

master.mainloop()

# --- executed after closing window ---

if login: # if login is True:
    print(bankUsername)
    print(bankPassword)
else:
    print("Canceled")