我是Tkinter的初学者,我正在尝试了解如何打开一个新窗口来计算一些变量。
在此示例中,出现带有按钮的第一个窗口(“输入”)。按下“开始”后,将创建一个新窗口,我可以导入圆周值,按直径转换按“转换”按钮。
当我按下此按钮时,控制台中会出现错误:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1470, in __call__
return self.func(*args)
File "C:/Users/samsung/PycharmProjects/test_FirstDensity/openANDread.py", line 55, in convert
convert = tk.Button(c2d, text="Convert", command=convert_c2d, activeforeground="red")
UnboundLocalError: local variable 'convert_c2d' referenced before assignment
我尝试了几种解决方案而没有解决我的问题。
我的代码是:
from __future__ import division
from Tkinter import *
from math import pi
import tkMessageBox
import Tkinter, Tkconstants, tkFileDialog
from numpy import nan
import Tkinter as tk
class MainWindow(Frame):
def __init__(self):
Frame.__init__(self)
self.filename = None
self.master.title("input")
self.master.minsize(250, 150)
self.grid(sticky=E+W+N+S)
top=self.winfo_toplevel()
top.rowconfigure(0, weight=1)
top.columnconfigure(0, weight=1)
for i in range(1): self.rowconfigure(i, weight=1)
self.columnconfigure(1, weight=1)
self.button0 = Button(self, text="start", command=self.convert, activeforeground="red")
self.button0.grid(row=0, column=1, pady=2, padx=2, sticky=E+W+N+S)
def convert(self):
c2d = Tk()
c2d.title("C2DBH converter")
c2d.minsize(350, 150)
c2d.grid()
res = StringVar(c2d)
res.set("---")
for i in range(3): c2d.rowconfigure(i, weight=1)
c2d.columnconfigure(1, weight=1)
label_c = tk.Label(c2d, text='Circumference')
label_c.grid(row=0, column=0, padx=2, sticky=E+W+N+S)
entry_c = Entry(c2d)
entry_c.grid(row=0, column=1, padx=2,sticky=E+W+N+S)
label_d = tk.Label(c2d, text='Diameter')
label_d.grid(row=1, column=0, padx=2, sticky=E+W+N+S)
result = tk.Label(c2d, textvariable=res, fg="red")
result.grid(row=1, column=1, pady=2, padx=2, sticky=E+W+N+S)
convert = tk.Button(c2d, text="Convert", command=convert_c2d, activeforeground="red")
convert.grid(row=2, column=0, columnspan=2, pady=2, padx=2, sticky=E+W+N+S)
def convert_c2d(n):
if not n.get():
return res.set("Insert a numeric value.")
try:
c = float(n.get())
diameter = c/pi
return res.set(str(diameter))
except ValueError:
return res.set("Insert a numeric value.")
答案 0 :(得分:3)
您应该在引用之前定义该函数。
>>> def f():
... convert_c2d(1)
... def convert_c2d(n):
... pass
...
>>> f()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in f
UnboundLocalError: local variable 'convert_c2d' referenced before assignment
>>> def g():
... def convert_c2d(n):
... pass
... convert_c2d(1)
...
>>> g()
>>>
只需更改以下代码即可解决问题:
def convert_c2d(n):
if not n.get():
return res.set("Insert a numeric value.")
try:
c = float(n.get())
diameter = c/pi
return res.set(str(diameter))
except ValueError:
return res.set("Insert a numeric value.")
convert = tk.Button(c2d, text="Convert", command=convert_c2d, activeforeground="red")
convert.grid(row=2, column=0, columnspan=2, pady=2, padx=2, sticky=E+W+N+S)
<强>更新强>
convert_c2d
需要一个参数。但是tkinter不会使用参数调用命令回调。你应该使用另一个函数(或下面的lambda)传递它:
convert = tk.Button(c2d, text="Convert", command=lambda: convert_c2d(entry_c),
activeforeground="red")
或者您可以更改convert_c2d
不接受任何参数,并使该函数直接访问entry_c
。 (嵌套函数可以从封闭范围访问变量)。