我正在尝试设置在“on_button”函数中计算的区域和周长变量的值,并在标签中使用它们。我对在代码中使用全局感到困惑,因为有人说它不好。
import Tkinter as tk
class SampleApp(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.area = 0
self.widthLabel = tk.Label(self, text="Width:")
self.widthLabel.grid(row=0, column=0)
self.widthEntry = tk.Entry(self)
self.widthEntry.grid(row=0, column=1)
self.heightLabel = tk.Label(self, text="Height:")
self.heightLabel.grid(row=1, column=0)
self.heightEntry = tk.Entry(self)
self.heightEntry.grid(row=1, column=1)
#self.areaValLabel = tk.StringVar()
#self.areaValLabel.set(0)
self.areaLabel = tk.Label(self, text="Area:").grid(row=3, column=0)
self.areaValLabel = tk.Label(self, textvariable=self.area).grid(row=3, column=1)
self.PerLabel = tk.Label(self,text="Perimeter:").grid(row=4, column=0)
#self.perValLabel =tk.Label(self, text=perimeter).grid(row=4, column=1)
self.button = tk.Button(self, text="Calculate", command=self.on_button).grid(row=2, column=0)
def on_button(self):
print self.widthEntry.get()
print self.heightEntry.get()
width = self.widthEntry.get()
height = self.heightEntry.get()
print float(width)*float(height)
self.area.set(float(width)*float(height))
app = SampleApp()
app.title("HW1")
app.mainloop()
答案 0 :(得分:-3)
您可以像这样访问变量:
self.area.set(float(self.width)*float(self.height))
即使在外面你也可以这样做:
object.width
获取参数的值。不需要全局:)