Shanky
Shanky

Reputation: 213

Python - tkinter - How to call a method in command argument

I am trying to write the below code, but it was not working as expected

Question : I want first to display the Login button in tkinter window, then a popup shoul come as Enter Credentials,

But as i am trying to call the method in command argument, first the "Enter Credentials" popup is coming and then "Login" button is appearing with no effect in that button.

Please suggest how to call the login button in this case.

Here goes the code:

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()

Upvotes: 1

Views: 1122

Answers (1)

PRMoureu
PRMoureu

Reputation: 13327

The issue comes from how you declare the function export to display the popup, it makes a call to the sample method, which shows the messagebox, that's why you get the pop up too soon.

As a quick fix, replace the export thing by a lambda, directly in the command :

self.button = tk.Button(self,
                        text="Login",
                        command=lambda : self.sample(username, password))

Upvotes: 1

Related Questions