python函数抱怨没有定义全局变量

时间:2014-11-21 23:27:53

标签: python-3.x tkinter

当我将代码移动到函数中时,计算现在不起作用。抱怨: NameError:全局名称'脚'没有定义 我如何解决这个问题,以便方法正确地看到变量?

from tkinter import * # Import tkinter
from tkinter import ttk

def calculate(*args):
    try:
        value = float(feet.get())
        meters.set((0.3048 * value * 10000.0 + 0.5)/ 10000.0)
    except ValueError:
        pass

def frame():
    mainframe = ttk.Frame(root, padding = "3 3 12 12")
    mainframe.grid(column = 0, row = 0, sticky = (N, W, E, S))
    mainframe.columnconfigure(0, weight = 1)
    mainframe.rowconfigure(0, weight = 1)

    feet = StringVar()
    meters = StringVar()
    feet_entry = ttk.Entry(mainframe, width = 7, justify = CENTER, textvariable = feet)
    feet_entry.grid(column = 2, row = 1, sticky = (W, E))
    ttk.Label(mainframe, textvariable = meters).grid(column = 2, row = 2, sticky = (W, E))
    ttk.Button(mainframe, text = "Calculate", command = calculate).grid(column = 3, row = 3, sticky = (W))

    ttk.Label(mainframe, text = "feet").grid(column = 3, row = 1, sticky = (W))
    ttk.Label(mainframe, text = "is equivalent to:").grid(column = 1, row = 2, sticky = (E))
    ttk.Label(mainframe, text = "meters").grid(column = 3, row = 2, sticky = (W))

    for child in mainframe.winfo_children(): child.grid_configure(padx = 5, pady = 5)
    feet_entry.focus()
    root.bind('<Return>', calculate)

# create a Tkinter window
root = Tk()
root.title("Menu Bar")
frame()

# start the event loop
root.mainloop()

1 个答案:

答案 0 :(得分:0)

通过feetmeters替换它们来制作self.feetself.meters个实例属性,以获取

        value = float(self.feet.get())
        self.meters.set((0.3048 * value * 10000.0 + 0.5)/ 10000.0)
    ...
    self.feet = StringVar()
    self.meters = StringVar()
    feet_entry = ttk.Entry(mainframe, width = 7, justify = CENTER,
                           textvariable = self.feet)
    feet_entry.grid(column = 2, row = 1, sticky = (W, E))
    ttk.Label(mainframe, textvariable = self.meters
             ).grid(column = 2, row = 2, sticky = (W, E))