如何从 tkinter 中的自定义表单中检索条目值

huangapple go评论56阅读模式
英文:

How to retrieve entry value in tkinter from a custom form

问题

写了一个自定义的框架类,这样我可以轻松生成标签、输入框等。
我可以输入我希望每个表单具有的标签、输入框的数量。通过创建类的不同实例,我不需要每次都写很多标签和输入框。
但是当我运行代码时什么都不会发生。我没有错误可以指导我。
如果我在 get_first_entry(self) 函数中放置一个打印语句,那么它会打印出输入框中的值,但是我想要从类外部访问该值。

英文:

Wrote a custom frame class so I can easily generate labels, entries etc.
I can input the number of labels, entries I want each form to have. By creating different instances of the class I don't need to write lots of labels and entries each time.
But when I run the code nothing happens. I get no error to guide me.
If I place a print statement in get_first_entry(self) function then it prints the value from the entry, but I would like to access the value from outside the class.

import tkinter as tk

class MyFrame(tk.Frame):
    def __init__(self, parent, num_labels, num_entries, num_buttons, label_names=None, *args, **kwargs):
        super().__init__(parent, *args, **kwargs)
        
        # If label names are provided, use them instead of default labels
        if label_names is None:
            label_names = [f"Label {i+1}" for i in range(num_labels)]
        
        # Create labels and entries
        self.entries = []
        
        
        for i in range(num_labels):
            label = tk.Label(self, text=label_names[i])
            label.grid(row=i, column=0)
        
        
        for i in range(num_entries):
            entry = tk.Entry(self)
            entry.grid(row=i, column=1)
            self.entries.append(entry)
        
        # Create buttons

        for i in range(num_buttons):
            if i == 0:
                button = tk.Button(self, text=f"Get RA", command=self.get_first_entry)
            elif i == 1:
                button = tk.Button(self, text=f"Get DEC", command=self.get_second_entry)
            #else:
                #button = tk.Button(self, text=f"Button {i+1}")
            button.grid(row=num_labels+i, column=0, columnspan=2, pady=2)
    
    def get_first_entry(self):
        value = self.entries[0].get()
        return value
       
        
    def get_second_entry(self):
        value = self.entries[1].get()
        return value



root = tk.Tk()
label_RADEC = ['RA','DEC']
label_Time = ['LST','local time']
# Create first frame
frame1 = MyFrame(root, num_labels=2, num_entries=2, num_buttons=2, label_names=label_RADEC)
frame1.grid(row=0, column=0, padx=10, pady=10)

# Access the first entry
first_entry_value = frame1.get_first_entry()

print(first_entry_value)

root.mainloop()

Updated with method to gel all entries as array.
Now it prints empty array at start, but if I input other values in the entries, still doesn't print anything

'',''

答案1

得分: 0

以下是翻译好的部分:

问题不在于 get_entries 函数不起作用,而是你在错误的方式中使用它。

当你首次调用 get_entries 并打印结果时,这是在用户有机会输入任何内容之前,所以它会打印一个空字符串列表。

当你通过按按钮来调用 get_entries 时,它会计算值得很好。然而,因为它只返回值,这些值会被丢弃,因为调用者(mainloop)忽略了它调用的所有函数的返回值,因为它不知道如何处理它们。

你可以通过在 get_entries 函数内添加一个 print 语句来查看这一点。当你这样做时,你可以看到它获得了值:

def get_entries(self):
    result = [entry.get() for entry in self.entries]
    print(f"get_entries result: {result}")
    return result

当我在第一个输入框中插入 "this is RA",在第二个输入框中插入 "this is DEC" 时,当我按按钮时,我会得到以下输出:

get_entries result: ['this is RA', 'this is DEC']

如果保留 return 语句,你可以在类外部获取这些值。只是你必须在用户输入值之后而不是之前这样做。

英文:

The problem isn't that get_entries isn't working, it's that you're using it in the wrong way.

When you first call get_entries and print the results, it's before the user has had a chance to enter anything so it prints a list of empty strings.

When you call get_entries by pressing the button, it computes the values just fine. However, because it only returns the values, the values are thrown away since the caller (mainloop) ignores the return values of all functions it calls since it doesn't know what to do with them.

You can see this by adding a print statement inside get_entries. When you do that, you can see it's getting the values just fine:

def get_entries(self):
    result = [entry.get() for entry in self.entries]
    print(f"get_entries result: {result}")
    return result

When I insert "this is RA" in the first entry, and "this is DEC" in the second entry, when I press the button I get this output:

get_entries result: ['this is RA', 'this is DEC']

If you leave the return statement in, you can use it to get the values outside of the class. It's just that you must do so after the user has entered values and not before.

huangapple
  • 本文由 发表于 2023年2月19日 23:35:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/75501257.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定