如何在不预定义可以输入的值数的情况下将多个项目追加到列表中?

时间:2019-04-23 20:28:50

标签: python python-3.x tkinter

我正在尝试使用pythons tkinter作为gui将项目添加到列表中。用户可以选择他们想要输入的值的数量,程序应将这些项目分别保存到同一列表中。当前该程序仅将用户输入的最后一个值附加到列表中。例如,当前如果用户选择输入2个值,则仅将第二个值添加到列表中。我已经在下面发布了我的确切代码。如果有人指出我正确的方向,我将不胜感激。

def multiple_chords_num():
    global num_chords_screen
    num_chords_screen = tk.Toplevel(root)
    num_chords_screen.grab_set()

    # geometry
    center_screen(300, 250, num_chords_screen)

    # other screen settings
    num_chords_screen.title('Transposition Tool')
    num_chords_screen.resizable(width = False, height = False)

    tk.Label(num_chords_screen,text = '\n\nHow Many Chords Would you like to Transpose?\n').pack()

    num=tk.Entry(num_chords_screen)
    num.pack()#pevents from object returning 'None'

    tk.Label(num_chords_screen,text = '').pack()
    ttk.Button(num_chords_screen, text = 'OK', command = lambda: multiple_chords(num)).pack(ipadx = 10, ipady = 1)

def multiple_chords(num):

    global multiple_chords_screen
    multiple_chords_screen = tk.Toplevel(root)
    multiple_chords_screen.grab_set()

    # geometry
    center_screen(300, 250, multiple_chords_screen)

    # other screen settings
    multiple_chords_screen.title('Transposition Tool')
    multiple_chords_screen.resizable(width = False, height = False)

    num=int(num.get())#obtains num value and turns it into integer
    for i in range(0,num):
        tk.Label(multiple_chords_screen,text = 'Enter Chord:').pack()
        chord=tk.Entry(multiple_chords_screen)
        chord.pack()#Prevents 'chord' from returning None


    ttk.Button(multiple_chords_screen, text = 'OK', command =lambda : a(chord.get(),num)).pack(ipadx = 10, ipady = 1)


def a(chord):
    u_list.append(chord)
    print(u_list)

1 个答案:

答案 0 :(得分:0)

chord只能保留一个元素。在每个循环中,您都将新的Entry分配给该变量,因此最终它仅保留最后的Entry

您必须将所有Entry保留在列表中,然后将此列表发送给功能a

函数a需要使用for循环从每个Entry获取值并将其追加到u_list

或多或少:

    # list for all entry    
    all_entry = []

    for i in range(0,num):
        tk.Label(multiple_chords_screen,text = 'Enter Chord:').pack()
        chord=tk.Entry(multiple_chords_screen)
        chord.pack()#Prevents 'chord' from returning None
        # keep entry on list
        all_entry.appen(chord)

    # send all_entry to `a`
    ttk.Button(multiple_chords_screen, text='OK', command=lambda : a(all_entry, num)).pack(ipadx = 10, ipady = 1)


def a(all_entry):
    # get all values
    for entry in all_entry:
        u_list.append(entry.get())
    print(u_list)