繁体   English   中英

在 Tkinter 输入框的实例名称中使用变量

[英]Using a Variable in the Instance Name of a Tkinter Entry Box

我正在尝试使用一个变量作为 tkinter Entry 框的实例名称,这样当我通过 for 循环进行随机播放时,每个框都有一个唯一的实例名称。 有没有办法做到这一点,以便以后我可以提取单个条目值?

    hoursList = [1, 2, 3, 4, 5]
    x = 0
    for item in hoursList:
        varName = "userEntry" + str(x)
        self.varName = tk.Entry(self.frame)
        self.varName.grid()
        x += 1
    self.getInput = tk.Button(self.frame, text="Submit", command= self.submitHours())
    self.getInput.grid()

def submitHours(self):
    if self.varName.get() is not None:
        print(self.varName.get())

理想情况下,该段将创建 5 个名为“userEntry1”、“userEntry2”等的条目框,并打印每个提交的值。

如果可以,尽量避免动态创建变量名。 这是可能的,但实现通常是复杂的,并且随着您的代码库变得越来越复杂,可能会导致难以理解代码。 相反,使用像list这样的容器来保存所有条目。 它们不需要有名字,你只需要能够引用它们。

此外,您的command = self.submit_hours()并没有按照您的想法行事。 正如所写, self.submit_hours将在您创建提交按钮时运行。 您想将可调用对象传递给命令(如函数)。 单击按钮时,您传递给 command 的任何内容都将被调用 要在您的代码中解决此问题,只需删除self.submit_hours()上的括号,因为self.submit_hours本身是可调用的。

下面是一个显示如何将您的条目存储在列表中、如何访问它们以及它们如何与您的hour_list对应的hour_list示例。

import tkinter as tk

class MyApp:
    def __init__(self):
        self.root = tk.Tk()
        self.frame = tk.Frame(master = self.root)
        self.frame.grid()
        self.hour_list = [1, 2, 3, 4, 5]
        self.entries = []
        self.make_entries()
        self.root.mainloop()


    def submit_hours(self):
        for n, entry in enumerate(self.entries):
            print(f"Entry {n} (hour {self.hour_list[n]}) has the value '{entry.get()}'")
        return

    def make_entries(self):
        for hour in self.hour_list:
            temp_entry= tk.Entry(master = self.frame)
            temp_entry.grid()
            self.entries.append(temp_entry)
        self.submit_button = tk.Button(master = self.frame, text = "Submit",
                                       command = self.submit_hours)
        self.submit_button.grid()
        return

test = MyApp()

当我在条目中输入内容然后点击提交按钮时,这是我的控制台输出:

Entry 0 (hour 1) has the value 'first box'
Entry 1 (hour 2) has the value 'this is the 2nd'
Entry 2 (hour 3) has the value 'and the third box'
Entry 3 (hour 4) has the value 'fourth'
Entry 4 (hour 5) has the value '5th'

暂无
暂无

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

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