简体   繁体   中英

How to Make Tkinter Entries from An Entry Box into A Python List

I have a entry box that allows users to input multiple integers separated by commas. How do I get the entries from this entry box into a python list which I can store as a variable.

Thanks in advance.

PSIf you require specific examples of code please reply and ask me.

There are a number of different ways that you could do this. The first and "simplest" is using split() .

from tkinter import *

root = Tk()

def command():
    print(entry.get().split(" "))

entry = Entry(root)
button = Button(root, text="Print", command=command)

entry.pack()
button.pack()

root.mainloop()

In the above snippet we simply call split() on the value of the Entry (which is returned from entry.get() ) using " " (the space character) as our delimiter. So every word separated by a space character is placed into it's own element in the list .

We could do this with any delimiter, if for example you wanted to have each element separated by a comma character, you would simply update the delimiter to "," or if you wanted to remove the space as well ", " .


Another way of doing this, which I would argue is more user friendly is to have a different Entry widget for each element of the list.

from tkinter import *

root = Tk()

labels = [Label(root, text="Value1:"), Label(root, text="Value2:"), Label(root, text="Value3:"), Label(root, text="Value4:"), Label(root, text="Value5:")]
entries = [Entry(root), Entry(root), Entry(root), Entry(root), Entry(root)]

for label, entry in zip(labels, entries):
    label.pack()
    entry.pack()

def command():
    print([entry.get() for entry in entries])

Button(root, text="print", command=command).pack()

root.mainloop()

This will cycle through each of the Entry widgets whenever the Button is pushed and return a list of their contents.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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