【问题标题】:How can I get input from multiple entry widgets created in a loop?如何从循环中创建的多个条目小部件中获取输入?
【发布时间】:2020-02-18 14:42:31
【问题描述】:

我已经搜索了之前的一些答案,并且更进一步,但我的问题是仍然我无法从多个输入框中获得 值。

import tkinter as tk
from tkinter import ttk
window = tk.Tk()
my_list = []

def get_info():
    for each_player in my_list:
        tk.Label(window, text=temp_entry.get()).grid()

#number of players is determined by the user.
#In this example, lets say there are 3 players
tk.Label(window, text="Number of Players: ").grid()
num_of_players = ttk.Combobox(window, values=[1, 2, 3])
num_of_players.current(2)
num_of_players.grid(row=0, column=1)
#The code above is only the recreate the user selecting the amount of players from a combobox


#create number of entry boxes for user-determined number of players
for each_player in range(1, int(num_of_players.get()) + 1):
    temp_label = tk.Label(window, text="Player {}: ".format(each_player))
    temp_entry = tk.Entry(window)
    my_list.append(temp_entry)

    temp_label.grid(row=each_player, column=0, pady=10)
    temp_entry.grid(row=each_player, column=1, pady=10)
button = tk.Button(window, text="Save", command=get_info)
button.grid()

window.mainloop()

在代码的结尾,我很难找出如何从输入框中获取信息。我如何才能使用 get() 方法,但只有在用户输入文本之后?

【问题讨论】:

    标签: python for-loop tkinter get tkinter-entry


    【解决方案1】:

    您的列表包含条目小部件,因此在循环中您需要引用循环变量而不是temp_entry

    def get_info():
        for each_player in my_list:
            print(each_player.get())
    

    【讨论】:

    • 啊,做到了。感谢您的帮助!
    【解决方案2】:

    使用按钮触发获取文本的方法,例如:

    play = Button(window, text="get_button", command=that_getter_method)
    .....
    .....
    def that_getter_method():
        var = field.get()
    

    【讨论】:

    • 我已经重写了代码以包含一个按钮。现在它只打印最后一个输入框。
    • 因为你没有使用文本字段数组,而是你一遍又一遍地使用相同的变量......最后一次迭代设置了该字段的值,因此你得到的文本只有最后一个..希望这可以帮助你解决你的问题:D ;)..
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-19
    • 2015-12-14
    • 2020-08-03
    • 2015-04-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多