Reputation: 21
I am trying to write a function that adds the user's chosen numbers and displays the sum after every button click. This function is a part of a bigger program. Hence I have to put it in a class or a fuction.
The program works when it's outside the function
import Tkinter as tk
total = 0
def Sum():
global total
num = var.get()
total = num+ total
label.config(text = total)
root = tk.Tk()
var = tk.IntVar()
numbers = [("1"),
("2"),
("3"),
("4"),
("5")]
for val, choice in enumerate(numbers):
tk.Radiobutton(root,
text=choice,
indicatoron = 0,
width = 5,
padx = 100,
variable=var,
command=Sum,
value=val).pack()
label = tk.Label(root, width = 30, height = 3, bg = "yellow")
label.pack()
root.mainloop()
But when I put it inside a function like this
import Tkinter as tk
def func():
total = 0
def Sum():
global total
num = var.get()
total = num+ total
label.config(text = total)
root = tk.Tk()
var = tk.IntVar()
numbers = [("1"),
("2"),
("3"),
("4"),
("5")]
for val, choice in enumerate(numbers):
tk.Radiobutton(root,
text=choice,
indicatoron = 0,
width = 5,
padx = 100,
variable=var,
command=Sum,
value=val).pack()
label = tk.Label(root, width = 30, height = 3, bg = "yellow")
label.pack()
root.mainloop()
func()
it throws me the following error:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1532, in __call__
return self.func(*args)
File "C:\Python27\Gui_demo.py", line 9, in Sum
total = num+ total
NameError: global name 'total' is not defined
I'm new to Python and was hoping there's a simple workaround. Any help would be appreciated. Thanks
Upvotes: 0
Views: 646
Reputation: 36732
My suggestion is to place your app in a class instead of nested functions.
class App:
total = 0
def __init__(self):
root = tk.Tk()
self.var = tk.IntVar()
numbers = [("1"),
("2"),
("3"),
("4"),
("5")]
for val, choice in enumerate(numbers):
tk.Radiobutton(root,
text=choice,
indicatoron = 0,
width = 5,
padx = 100,
variable=self.var,
command=self.Sum,
value=val+1).pack()
self.label = tk.Label(root, width = 30, height = 3, bg = "yellow")
self.label.pack()
root.mainloop()
def Sum(self):
num = self.var.get()
App.total += num
self.label.config(text = App.total)
App()
Upvotes: 1