114
114

Reputation: 926

Changing Syntax for List Entries in Python (Tkinter)

I have a small application that takes in a string of numbers, runs them through a function, and spits out the output. For the list entry I have the following set up:

 def create_widgets(self):
        self.entryLabel = Label(self, text="Please enter a list of numbers:")
        self.entryLabel.grid(row=0, column=0, columnspan=2)      

        self.listEntry = Entry(self)
        self.listEntry.grid(row=0, column=2, sticky=E)

However, this only allows me to input strings (e.g. 123451011) while I would like it to be able to recognize individual numbers (e.g. 1,2,3,4,5,10,11). I suppose essentially what I'm asking is to be able to use a list instead of a string. Is there a way to change self.listEntry to handle this? Is there something I can add into my function instead (which currently inputs valueList = list(self.listEntry.get()))? Thanks!

EDIT:

I defined a function as follows:

    def Function(self):
        valueList = list([int(x) for x in self.listEntry.get().split(",")])
        x = map(int, valueList)

Which then continues to outline how to run the numbers and tells the program to give the output.

Upvotes: 1

Views: 918

Answers (2)

user2555451
user2555451

Reputation:

You can do something like this:

import Tkinter as tk

root = tk.Tk()

entry = tk.Entry()
entry.grid()

# Make a function to go and grab the text from the entry and split it by commas
def get():
    '''Go and get the text from the entry'''

    print entry.get().split(",")

# Hook the function up to a button
tk.Button(text="Get numbers", command=get).grid()

root.mainloop()

Or, if you want them all to be integers, change this line:

print entry.get().split(",")

to this:

print map(int, entry.get().split(","))

Upvotes: 2

user1612868
user1612868

Reputation: 541

You can just use split on the input, and then map int to the list that that generates.

self.listEntry = [int(x) for x in Entry(self).split(',')]

Upvotes: 0

Related Questions