Home > Software engineering >  Insert multiple input in one entry Tkinter
Insert multiple input in one entry Tkinter

Time:02-23

I got a task where I'm supposed to create a summation calculator using tkinter and I end up with this code below:

import tkinter as tk
from tkinter import *

window = Tk()
window.geometry('300x250')
window.title('Summation')

insert_n = tk.Entry(window)
insert_n.pack()

def sum_input():
    sum_input = int(insert_n.get())
    print(sum(sum_input))

button = tk.Button(window,text='Sum',command=sum_input)
button.pack()

window.mainloop()

What I'm trying to achieve is lets say when the user entered 1,2,3,4 in the entry where the sum of the input value will be printed out on my console after the 'Sum' button is pressed, so in this case the output should be 10.

How do I do that?

CodePudding user response:

You need to split the input into individual number string and convert them to integers:

def sum_input():
    numbers = [int(x.strip()) for x in insert_n.get().strip().split(',')]
    print(sum(numbers))

CodePudding user response:

try this but you need to make some validation to the input

def sum_input():
    sum_input = insert_n.get()
    #split the string into list
    sum_list=sum_input.split(',')
    #convert to integer
    sum_list=[int(index) for index in sum_list]
    print(sum(sum_list))

  • Related