我正在尝试编写以下代码,但它没有按预期工作
问题: 我想首先在tkinter窗口中显示Login按钮,然后弹出窗口作为Enter Credentials,
但是当我试图在命令参数中调用方法时,首先输入"输入凭证" popup即将来临"登录"按钮出现在该按钮中没有任何效果。
请在此情况下建议如何拨打登录按钮。
以下是代码:
import sys
import tkinter.messagebox as box
from tkinter.filedialog import asksaveasfile
if sys.version_info[0] >= 3:
import tkinter as tk
else:
import Tkinter as tk
class App(tk.Frame):
def __init__(self, master, username, password):
tk.Frame.__init__(self, master)
self.dict = {'Asia': ['Japan', 'China', 'Malaysia'],
'Europe': ['Germany', 'France', 'Switzerland']}
self.variable_a = tk.StringVar(self)
self.variable_b = tk.StringVar(self)
self.variable_a.trace('w', self.update_options)
self.variable_b.trace('w', self.fun2)
self.optionmenu_a = tk.OptionMenu(self, self.variable_a, *self.dict.keys(), command=self.fun)
self.optionmenu_b = tk.OptionMenu(self, self.variable_b, '')
export = self.sample(username, password)
self.button = tk.Button(self,text="Login", command=export)
self.variable_a.set('Asia')
self.optionmenu_a.pack()
self.optionmenu_b.pack()
self.button.pack()
self.pack()
def fun(self,value):
print(value)
def fun2(self, *args):
print(self.variable_b.get())
def sample(self, username, password):
box.showinfo('info', 'Enter Credentials')
def update_options(self, *args):
countries = self.dict[self.variable_a.get()]
self.variable_b.set(countries[0])
menu = self.optionmenu_b['menu']
menu.delete(0, 'end')
for country in countries:
menu.add_command(label=country, command=lambda nation=country: self.variable_b.set(nation))
if __name__ == "__main__":
root = tk.Tk()
username = "root"
password = "admin"
app = App(root, username, password)
app.mainloop()
答案 0 :(得分:1)
问题来自于您如何声明函数export
以显示弹出窗口,它会调用显示消息框的sample
方法,这就是您太快弹出窗口的原因。
作为快速解决方案,直接在命令中用lambda替换export
事物:
self.button = tk.Button(self,
text="Login",
command=lambda : self.sample(username, password))