【问题标题】:How to split iterative tkinter Entry widgets into usable variables?如何将迭代 tkinter Entry 小部件拆分为可用变量?
【发布时间】:2018-06-22 01:32:08
【问题描述】:

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

到目前为止,我已经能够创建窗口并生成输入框、标签和按钮的开头,并尝试使用附加代码检查值。我当前的问题是找到某种方法将 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”的迭代.

【问题讨论】:

    标签: python python-3.x tkinter


    【解决方案1】:

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

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

    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()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-26
      • 1970-01-01
      • 2014-09-26
      相关资源
      最近更新 更多