如何将迭代的Tkinter Entry小部件拆分为可用变量?

时间:2018-06-22 01:32:08

标签: python python-3.x tkinter

我想使用类/字典结构创建一个用于数据存储的模板,这将允许我生成X值的字典,然后在tkinter窗口中编辑这些值,该窗口被设置为生成X条目小部件。

到目前为止,我已经能够创建窗口并生成输入框,标签和按钮的开头,并尝试使用附带的代码进行值检查。我当前的问题是找到一种将Entry小部件拆分为具有单独名称的单独实体的方法。我目前的尝试是让我尝试将键值从testDict连同条目值一起馈入storeDict。

    from tkinter import *

data = Tk()

# This sequence controls the label names and by extension the number of 
#widgets in the frame because each one is iterated through the for loop
test_seq = ['Sample1','Sample2','Sample3','Sample4','Sample5',
            'Sample6','Sample7','Sample8','Sample9','Sample10','Sample11',]



class Generator():

    def __init__(self, master, sequence,r,c): #r and c for row and column

       #Take a sequence and turn it into a dictionary with only keys
       testDict = dict.fromkeys(sequence,'' )

       #Set up the save button in the frame
       save_button = Button(master, text='Save Values',command=savevalues)
       save_button.grid(row=r, column=c)

       for key in testDict:
           r=r+1
           c=c
           label = Label(master,text = key + ' :')
           label.grid(row=r, column=c)
           entry = Entry(master)
           entry.bind("<Return>",checknumber("<Return>",entry))
           entry.grid(row =r,column =c+1)
           # storeDict = dict(key,entry.get()) #AN attempt at making a new 
           #dict to store the entry info


           # Limits the size of the frame to 11 rows including 0
           if r==10:
               r=0
               c=c+2
#Beginning of button setup
def savevalues():
        print('Hello, World!')

#Setting up the widgets to only accept float values. Otherwise return ERROR
def checknumber(event,entry):
    print('Hello, again!')
    try:
         float(entry.get())
    except ValueError:
         entry.configure(text= 'ERROR')

testObj = Generator(data, test_seq, 0, 0)

data.mainloop()

当前状态下的代码在运行时确实显示了问题,因为我尝试设置值检查时所有小部件都显示相同的文本,因为它们都是for循环中变量“ entry”的迭代

1 个答案:

答案 0 :(得分:0)

validatecommand功能是用于验证的绑定的替代方法。它可以解决用户输入时的验证问题。 http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/entry-validation.html

如果使用Entry小部件的'name'属性,则可以将输出数据构造为键入到输入标签的字典,这可能与您将数据作为字典对象传递的策略相匹配。

import tkinter as tk
from tkinter import ttk

ROOT = tk.Tk()
# example validation function
def _potential_float(num):
    max_one_dot = num.count('.') <= 1
    invalid = sum(1 for x in num if x not in '.0123456789')
    if max_one_dot and not invalid:
        return True
    return False
def getall_data():
    # dictionary of data matching test_seq input names
    data = {str(x).split('.')[-1]:x.get() for x in widget_reference}
    print(data)
    return data
test_seq = ['sample1','sample2','sample3','sample4','sample5',
            'sample6','sample7','sample8','sample9','sample10','sample11',]
frame = ttk.Frame(master=ROOT)
frame.grid()
widget_reference = []
# register the validation function
_is_float = frame.register(_potential_float)
# setup your labels and entries
for row, text in enumerate(test_seq):
    ttk.Label(master=frame,
              text=text).grid(column=0,
                              row=row)
    # specify the use of a validatecommand & attach name property
    temp = ttk.Entry(master=frame,
                     name=text,
                     validate='key',
                     validatecommand=(_is_float, '%P'))
    temp.grid(column=1,
              row=row)
    widget_reference.append(temp)
ttk.Button(master=frame,
           command=getall_data,
           text='collect data').grid(column=0,
                                     columnspan=2,
                                     row=11)
ROOT.mainloop()