如何在Tkinter Python中更新子函数内的标签

时间:2018-02-24 02:20:45

标签: python function tkinter radio-button label

我正在尝试编写一个功能,添加用户选择的数字,并在每次点击按钮后显示总和。此功能是更大程序的一部分。因此,我必须把它放在一个类或一个功能。

该程序在功能

之外时有效
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的新手,希望有一个简单的解决方法。任何帮助,将不胜感激。谢谢

1 个答案:

答案 0 :(得分:1)

我的建议是将您的应用程序放在一个类而不是嵌套函数中。

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()