【发布时间】:2018-08-04 03:35:52
【问题描述】:
我正在尝试编写一个添加用户选择的数字并在每次单击按钮后显示总和的函数。此功能是更大程序的一部分。因此我必须把它放在一个类或一个函数中。
程序在函数外运行
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()
但是当我把它放在这样的函数中时
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()
它抛出了以下错误:
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
我是 Python 新手,希望有一个简单的解决方法。任何帮助,将不胜感激。谢谢
【问题讨论】:
标签: python function tkinter radio-button label