Exercise 195
Create a graphical application in Python Tkinter that asks the user to enter an integer N and displays them the value of the sum "1 + 2 + ... + N" as shown in the figure below:
![](https://1.bp.blogspot.com/-hOeytL5-TXk/X1HTZTPbUsI/AAAAAAAABys/mHyV9UR8LUkoHVftC3cnuxOR4A_hMDHRwCLcBGAsYHQ/s1600/sum-of-prim-numbers-graphically-with-python-tkinter-python-courses.png)
Solution
from tkinter import *
def action():
# getting value of entryNumber
N = int(entryNumber.get())
# initialize sum
sum = 0
for i in range(1 , N + 1):
sum = sum + i
# display the sum "1 + 2 + 3 + ... + N" in label result
lblResult['text'] = "The sum is 1 + 2 + 3 + ... + " + str(N) + " = " + str(sum)
root = Tk()
root.geometry("450x150")
# creating label and entry text for number N
lblNumber = Label(root , text = "Enter value of integer N : ")
lblNumber.place( x = 20 , y = 20)
entryNumber = Entry(root)
entryNumber.place( x = 200 , y = 20 , width = 240)
# creating label to display result
lblResult = Label(root , text ="")
lblResult.place(x = 200 , y = 50 )
# creating button to perform the action
btnValidate = Button(root, text = " Validate" , command = action)
btnValidate.place(x = 200 , y = 90 , width = 240)
root.mainloop()
Younes Derfoufi
my-courses.net
my-courses.net