正在获取组合框中所有用户选择的值



我在一个组合框中创建了一个简单的循环,它可以创建动态数量的条目——这实际上取决于用户想要的过滤器数量。理想情况下,我想通过"提交"按钮存储所有用户做出的选择,但我似乎无法将变量传递到类模块内的">回调"函数中。因此,我只能存储最后一个组合框。我创建了一个">n"变量,可以方便地检索每个组合框。从本质上讲,我希望将所有这些选择存储在变量">user_selections"中。理想情况下,当面对用户选择时,该代码将被重新用作模板。

为了将来的参考,我还想探讨是否有可能在每个组合框中有多个用户选择,而不是一个下拉选择。我对python编码还很陌生,所以很难把东西组合在一起。

非常感谢您的帮助!以下代码:

import tkinter as tk
from tkinter import *
from tkinter import ttk
class User_ComboBox(Tk):
def __init__(self, s, options):
Tk.__init__(self)
self.title("User Selections: ")
x = s*100
y = s*50
self.geometry(str(x) + "x" + str(y) + '+350+350')

self.labelTop = tk.Label(self,text = "Data Slicing Options: ")
self.labelTop.grid(row = 0, column = 0, sticky = W, pady = 2)

for i in range(1, s+1):
n = "combobox_" + str(i)
self.label = Label(self,text="Select Criteria " + str(i))
self.label.grid(row = i, column = 0, sticky = W, pady = 2)
self.n = ttk.Combobox(self,values=options[i - 1])
self.n.grid(row = i, column = 1, sticky = W, pady = 2)

self.okButton = tk.Button(self, text='Submit',command = self.callback)
self.okButton.grid(row = i + 1, column = 0, sticky = W, pady = 2)

def callback(self):
""" Get the contents of the Entry and exit """
self.comboBox_contents = {'a':self.n.get()}
self.destroy()
def ComboboxSelection():
options = [['Layer 1','Layer 2','Layer 3'],['Americas','APAC','EMEA'],['Bank','Institution','Fund']]
n_comboboxes = 3
selection = User_ComboBox(n_comboboxes, options)
selection.mainloop()

return selection.comboBox_contents
user_selections = ComboboxSelection()

我已经编辑了下面的代码,这应该可以工作:

(请注意,我已经移走了一些东西,并稍微清洗了一下(。基本上,问题是你每次都试图重新分配给n,而你需要一个列表容器来附加每个n。

from tkinter import *
from tkinter import ttk
class User_ComboBox(Tk):
def __init__(self, s, options):
Tk.__init__(self)
self.title("User Selections: ")
self.comboBox_contents = []
self.comboBoxes = [[] for n in range(s)]
x = (s+1)*100
y = (s+1)*50
self.geometry(str(x) + "x" + str(y) + '+350+350')

self.labelTop = Label(self,text = "Data Slicing Options: ")
self.labelTop.grid(row = 0, column = 0, sticky = W, pady = 2)

for i in range(s):
self.label = Label(self,text="Select Criteria " + str(i))
self.label.grid(row = i+1, column = 0, sticky = W, pady = 2)
self.comboBoxes[i] = ttk.Combobox(self, values = options[i])
self.comboBoxes[i].grid(row = i+1, column = 1, sticky = W, pady = 2)

self.okButton = Button(self, text='Submit',command = self.callback)
self.okButton.grid(row = i + 2, column = 0, sticky = W, pady = 2)

def callback(self):
""" Get the contents of the Entry and exit """
self.comboBox_contents = [x.get() for x in self.comboBoxes]
self.destroy()
def ComboboxSelection():
options = [['Layer 1','Layer 2','Layer 3'],['Americas','APAC','EMEA'],['Bank','Institution','Fund']]
n_comboboxes = 3
selection = User_ComboBox(n_comboboxes, options)
selection.mainloop()

return selection.comboBox_contents
user_selections = ComboboxSelection()
print(user_selections)

另外,如果我正确理解你的第二个问题,我想你要找的是ListBox?

一般来说,尽量减少文本和代码,问题越短,阅读人数就越多!

相关内容

  • 没有找到相关文章

最新更新