Python - Tkinter - How to get the value from a dropdown option and pass to another function

时间:2017-08-05 12:33:58

标签: python tkinter

Please suggest how to use the selected drop down value in another function(sample()) in below code snippet.

I was able to create a two functions fun() and fun2() which returns the first dropdown value and second dropdown value, but i was unable to pass the selected dropdown value as a parameter.

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):
        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_b.trace('w', self.fun2)
        self.variable_a.trace('w', self.update_options)


        self.optionmenu_a = tk.OptionMenu(self, self.variable_a, *self.dict.keys(), command=self.fun)
        self.optionmenu_b = tk.OptionMenu(self, self.variable_b, '')


        username = self.fun()
        password = self.fun2()


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


        self.variable_a.set('Asia')

        self.optionmenu_a.pack()
        self.optionmenu_b.pack()
        self.button.pack()
        self.pack()

    def fun(self,*args):
        return self.variable_a.get()

    def fun2(self, *args):
        return self.variable_b.get()


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


def sample(username, password):
    box.showinfo('info', 'Enter Credentials')


if __name__ == "__main__":
    root = tk.Tk()
    username = "root"
    password = "admin"
    app = App(root)
    app.mainloop()

1 个答案:

答案 0 :(得分:1)

在第一次下拉调用之前调用其命令self.fun并调用self.variable_b.trace('w', self.fun2),因此下拉列表2将更改其值的速度超过1下拉列表,可以通过print in fun / fun2确认:

def fun(self,*args):
    print("value 1dd: " + self.variable_a.get())
    return self.variable_a.get()

def fun2(self, *args):
    print("value 2dd: " + self.variable_b.get())
    return self.variable_b.get()

我不会使用optionmenu,因为它无法获得焦点,您可以使用组合框,如果问题是Please suggest how to use the selected drop down value in another function,请查看此示例:

import sys
import tkinter.messagebox as box
from tkinter.filedialog import asksaveasfile
if sys.version_info[0] >= 3:
    import tkinter as tk
    import tkinter.ttk as ttk
else:
    import Tkinter as tk


class App(tk.Frame):

    def __init__(self, master):
        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.last_county = tk.StringVar(self)
        self.area = tk.StringVar(self)
        self.country = tk.StringVar(self)

        self.variable_b.trace('w', self.fun2)
        self.variable_a.trace('w', self.update_options)


        self.combobox_a = ttk.Combobox(self, values=list(self.dict.keys()), state='readonly')
        self.combobox_a.bind("<<ComboboxSelected>>", self.fun)
        self.combobox_a.current(0)
        self.combobox_b = ttk.Combobox(self, values=self.dict['Asia'], state='readonly')
        self.combobox_b.bind("<<ComboboxSelected>>", self.fun2)
        self.combobox_b.current(0)


        username = self.fun()
        password = self.fun2()


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


        # self.variable_a.set('Asia')

        self.combobox_a.pack()
        self.combobox_b.pack()
        self.button.pack()
        self.pack()

    def fun(self,*args):
        print("changed 1-st combobox value to: " + self.combobox_a.get())
        if self.last_county != self.combobox_a.get():
            self.combobox_b['values']=self.dict[self.combobox_a.get()]
            self.combobox_b.current(0)
        self.last_county = self.area = self.combobox_a.get()
        return self.variable_a.get()

    def fun2(self, *args):
        print("changed 2-nd combobox value to" + self.combobox_b.get())
        self.country = self.combobox_b.get()
        return self.variable_b.get()

    def update_options(self, *args):
        countries = self.dict[self.variable_a.get()]
        self.variable_b.set(countries[0])

        menu = self.combobox_b['menu']
        menu.delete(0, 'end')

        for country in countries:
            menu.add_command(label=country, command=lambda nation=country: self.variable_b.set(nation))


def sample(username, password, area, country):
    box.showinfo('info', 'Selected area: ' + area + '\nSelected country: ' + country + '\nEnter Credentials')

if __name__ == "__main__":
    root = tk.Tk()
    username = "root"
    password = "admin"
    app = App(root)
    app.mainloop()

我创建了两个变量self.areaself.country,它们从fun() / fun2()函数中获取其值,并展示了如何在sample()函数中使用它们。

更新

我不知道,但我猜你准备创造这样的东西:

import sys
import tkinter.messagebox as box
from tkinter.filedialog import asksaveasfile
if sys.version_info[0] >= 3:
    import tkinter as tk
    import tkinter.ttk as ttk
else:
    import Tkinter as tk


class App(tk.Frame):

    def __init__(self, master):
        tk.Frame.__init__(self, master)
        self.dict = {'Asia': ['Japan', 'China', 'Malaysia'],
                     'Europe': ['Germany', 'France', 'Switzerland']}
        # Init labels
        self.label_a = tk.Label(self, text="User Name: ")
        self.label_b = tk.Label(self, text="Password: ")
        # Initialize entries
        self.entry_a = tk.Entry(self)
        self.entry_b = tk.Entry(self, show='*') # Make a password entry
        # Add clear on double-click
        self.entry_a.bind("<Double-1>", lambda cl: self.entry_a.delete(0, "end"))
        self.entry_b.bind("<Double-1>", lambda cl: self.entry_b.delete(0, "end"))
        # Set default text
        self.entry_a.insert("0", "BladeMight")
        self.entry_b.insert("0", "lalala7x256")
        # Initialize comboboxes
        self.combobox_a = ttk.Combobox(self, values=list(self.dict.keys()), state='readonly')
        self.combobox_b = ttk.Combobox(self, values=self.dict['Asia'], state='readonly')
        # Select 0 element
        self.combobox_a.current(0)
        self.combobox_b.current(0)
        # Add event to update variables on combobox's value change event
        self.combobox_a.bind("<<ComboboxSelected>>", lambda f1: self.fun())
        self.combobox_b.bind("<<ComboboxSelected>>", lambda f2: self.fun2())
        # Initialize variables
        self.area = self.combobox_a.get()
        self.last_area = self.country = self.combobox_b.get()
        self.username = self.password = tk.StringVar(self)
        # Intialize button with command to call sample with arguments
        self.button = tk.Button(self, text="Login", command=lambda: sample(self.area, self.country, self.entry_a.get(), self.entry_b.get()))
        # Place all controls to frame
        self.label_a.pack()
        self.entry_a.pack()
        self.label_b.pack()
        self.entry_b.pack()
        self.combobox_a.pack(pady=5)
        self.combobox_b.pack(pady=5)
        self.button.pack()
        self.pack()

    def fun(self):
        print("changed 1-st combobox value to: " + self.combobox_a.get())
        if self.last_area != self.combobox_a.get():
            self.combobox_b['values']=self.dict[self.combobox_a.get()]
            self.combobox_b.current(0)
            self.country = self.combobox_b.get()
        self.last_area = self.area = self.combobox_a.get()

    def fun2(self):
        print("changed 2-nd combobox value to: " + self.combobox_b.get())
        self.country = self.combobox_b.get()

def sample(area, country, username, password):
    box.showinfo('info', 'User Name: ' + username + '\nPassword: ' + password + '\n' + 'Selected area: ' + area + '\nSelected country: ' + country + '\n')

if __name__ == "__main__":
    root = tk.Tk()
    username = "root"
    password = "admin"
    app = App(root)
    app.mainloop()

正确?

相关问题