简体   繁体   English

Python Tkinter如何从存储在一个变量中的多个Entry小部件中获取输入

[英]Python Tkinter how to take the input from multiple Entry widgets stored in one variable

my code is the following. 我的代码如下。

from tkinter import *
def TakeInput():
    print(tb.get()) #This will print Entry1 input
    print(tb.get()) #This will print Entry2 input
tk=Tk()
#Entry 1
tb=Entry(tk) #Both Entry1 and Entry2 are stored in the same variable: tb
tb.pack()
#Entry 2
tb=Entry(tk) #Both Entry1 and Entry2 are stored in the same variable: tb
tb.pack()
#Button
b=Button(tk,text="PrintInput",command= TakeInput)
b.pack()
tk.mainloop()

All I am trying to do is to display both entry 1 and entry 2 input when both are assigned to the same variable. 我要尝试做的是在将条目1和条目2输入都分配给同一变量时同时显示它们。

Note that I am a Python newbie. 请注意,我是Python新手。

Create a list containing the entries and loop through them. 创建一个包含条目的列表并遍历它们。

def print_input(*args):
    for entry in entries:
        print(entry.get())

entries = [Entry(tk) for _ in range(2)]
for entry in entries:
    entry.pack()

btn = Button(tk, text="Print", command=print_input)

In your version, you're assigning tb at first to one entry, then to the other. 在您的版本中,首先要将tb分配给一个条目,然后tb给另一个。 That's not how you store input from multiple widgets in one variable. 这不是将来自多个小部件的输入存储在一个变量中的方式。 You're just overwriting the reference to the first widget you have created and stored. 您只是覆盖了对已创建和存储的第一个小部件的引用。

If you want to do it automatically, you have to control strings in entry widgets when they modified. 如果要自动执行,则必须在修改条目小部件中的字符串时对其进行控制。 You can do it with StringVar . 您可以使用StringVar做到这一点。 You dont need a button, when the entry1's text equals to entry2's text, it will automatically prints. 您不需要按钮,当entry1的文本等于entry2的文本时,它将自动打印。

from tkinter import *

def TakeInput():
    print(tb1.get())
    print(tb2.get())

def on_entry1_changed(*args):
    if sv_entry1.get() == sv_entry2.get():
        TakeInput()

def on_entry2_changed(*args):
    if sv_entry1.get() == sv_entry2.get():
        TakeInput()
tk=Tk()

#Entry 1
sv_entry1 = StringVar()
sv_entry1.set("Entry1 text")
sv_entry1.trace("w", on_entry1_changed)

tb1=Entry(tk, textvariable=sv_entry1)
tb1.pack()

#Entry 2
sv_entry2 = StringVar()
sv_entry2.set("Entry2 text")
sv_entry2.trace("w", on_entry2_changed)

tb2=Entry(tk, textvariable=sv_entry2)
tb2.pack()

tk.mainloop()

If you want to do it with pressing button, you have to modify TakeInput function like this: 如果要通过按下按钮进行操作,则必须修改TakeInput函数,如下所示:

from tkinter import *
def TakeInput():
    if tb1.get() == tb2.get():
        print tb1.get()
tk=Tk()

#Entry 1
tb1=Entry(tk)
tb1.pack()

#Entry 2
tb2=Entry(tk)
tb2.pack()

#Button
b=Button(tk,text="PrintInput",command= TakeInput)
b.pack()
tk.mainloop()

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

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