在其他函数中设置全局变量

2024-05-13 21:10:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试设置面积和周长变量的值,这些值是在“on\ button”函数中计算出来的,并在标签中使用它们。我对在代码中使用global感到困惑,因为有些人说它不好。你知道吗

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

Tags: textselfgetoncolumnbuttonareafloat
1条回答
网友
1楼 · 发布于 2024-05-13 21:10:31

您可以这样访问变量:

self.area.set(float(self.width)*float(self.height))

即使在外面,你也可以这样做:

object.width

获取参数的值。不需要全局:)

相关问题 更多 >