[英]Python - Tkinter - How to get the value from a dropdown option and pass to another function
Please suggest how to use the selected drop down value in another function(sample()) in below code snippet. 请在下面的代码段中建议如何在另一个函数(sample())中使用所选的下拉值。
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. 我能够创建两个函数fun()和fun2(),它们返回第一个下拉值和第二个下拉值,但是我无法将所选的下拉值作为参数传递。
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()
Just before first dropdown call its command self.fun
an self.variable_b.trace('w', self.fun2)
is called, so dropdown 2 will change its value faster than 1 dropdown, that can be confirmed with print in fun/fun2: 就在第一个下拉菜单调用
self.fun
命令之前,调用了self.variable_b.trace('w', self.fun2)
,因此下拉菜单2的更改速度快于1个下拉菜单,可以通过fun / fun2中的print进行确认:
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()
I would not use the optionmenu
since it can't receive focus, you can use instead the combobox, also if the question is Please suggest how to use the selected drop down value in another function
then look this example: 我不会使用
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()
I created two variables self.area
and self.country
which gets its values from fun()
/ fun2()
functions, and showed how to use them in sample()
function. 我创建了两个变量
self.area
和self.country
,它们从fun()
/ fun2()
函数获取其值,并展示了如何在sample()
函数中使用它们。
Update : 更新 :
I don't know but i guessed that you are about to create something like this: 我不知道,但我猜想您将要创建这样的内容:
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()
right? 对?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.