简体   繁体   English

从按钮功能创建的对象中发出检索值的问题

[英]Issue retrieving values from objects created by button function

I'm working on a small project and I'm having issues retrieving the values stored in combo boxes. 我正在做一个小项目,在检索组合框中存储的值时遇到问题。 The program has a "plus" button that creates additional boxes beneath the existing ones. 该程序具有一个“加号”按钮,可在现有框的下方创建其他框。 They are created by calling a "create" function that makes a new instance of the ComboBox class, where the box is created and put onto the screen. 通过调用“创建”函数来创建它们,该函数创建ComboBox类的新实例,并在其中创建框并将其放到屏幕上。 A separate "submit" function is then supposed to loop through and retrieve all of the box values and store them in a list. 然后,应该使用一个单独的“提交”功能来循环并检索所有框值,并将它们存储在列表中。 My main flaw is that I used data in the variable names, but I have no clue how else to do this in this scenario. 我的主要缺陷是我在变量名中使用了数据,但是在这种情况下我不知道该如何做。 Does anyone have an alternative solution? 有人有替代解决方案吗?

(there are some off screen variables that are show used here as parameters, but there are definitely not the source of the issue) (这里显示了一些屏幕外变量作为参数,但绝对不是问题的根源)

class ComboBox:
    def __init__(self, master, counter, fields):
        self.master = master
        self.counter = counter
        self.fields = fields

        self.field_box = ttk.Combobox(width=20)
        self.field_box["values"] = fields
        self.field_box.grid(row=counter + 1, column=0, pady=5)

    def get_value(self):
        value = self.field_box.get()
        return value
def create():
    global entry_counter
    name = "loop"+str(entry_counter-1)
    name = ComboBox(window, entry_counter, fields)
    values.append(name.get_value())
    entry_counter += 1


def submit():
    for i in range(1, entry_counter):
        name = "loop" + str(entry_counter-1)
        values.append(name.get_value())

For example, if I created 2 boxes and selected the options "test1" and "test2" I would want the my values list to contain ["test1, "test2"] 例如,如果我创建了2个框并选择了选项“ test1”和“ test2”,我希望我的值列表包含["test1, "test2"]

Not sure I understand the question right, but I guess you are asking about how to loop throw all instances of ComboBox. 不确定我是否理解正确的问题,但是我想您正在询问如何循环抛出ComboBox的所有实例。 You can just create an global array, append new instance into it in create() method: 您可以只创建一个全局数组,然后在create()方法中向其添加新实例:

comboboxes = []
def create():
    ...
    comboboxes.append(new_instance)

def submit():
    for combobox in comboboxes:
        ...

You're on the right track with .get() . 您使用.get()正确的轨道上。 I believe your solution is that your get_value function also needs an event parameter: 我相信您的解决方案是您的get_value函数还需要一个event参数:

def get_value(self, event):
    value = self.field_box.get()
    return value

See the following: 请参阅以下内容:

Getting the selected value from combobox in Tkinter 从Tkinter的组合框中获取选定的值

Retrieving and using a tkinter combobox selection 检索和使用tkinter组合框选择

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM