Why is this code working I took from a textbook for GUI Python?
为什么这样不行?这是从课本上直接写的。我得到一个属性错误,说self。_区域不存在。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | from Tkinter import * import math class CircleArea(Frame): def __init__(self): """Sets up a window and widgets.""" Frame.__init__(self) self.master.title("Circle Area") self.grid() #Label and field for radius self._radiusLabel = Label(self, text ="Radius") self._radiusLabel.grid(row = 0, column = 0) self._radiusVar = DoubleVar() self._radiusEntry = Entry(self, textvariable = self._radiusVar) self._radiusEntry.grid(row = 0, column = 1) #Label and field for the area self._areaLabel = Label(self, text ="Area") self._areaLabel.grid(row = 1, column = 0) self._areaVar = DoubleVar() self._areaEntry = Entry(self, textvariable = self._areaVar) self._areaEntry.grid(row = 1, column = 1) # The command button self._button = Button(self, text ="Compute", command = self._area) self._button.grid(row = 2, column = 0, columnspan = 2) def _area(self): """Event handler for button.""" radius = self._radiusVar.get() area = radius ** 2 * math.pi self._areaVar.set(area) def main(): CircleArea(). mainloop() run = CircleArea() run.main() |
这是因为在调用后声明了u Area方法吗?这并不能解释为什么它不能使用向下向上编程技术。我对桂真的很陌生,刚开始学习。第一章是课堂上的图形用户界面。
edit*:我希望弹出一个窗口,并有一个输入字段用于输入圆的半径。标签半径。以及基于半径的圆面积结果的输出输入字段。底部有一个计算按钮。
我只是想习惯于输入不同的命令等等。我还没听过这个讲座。我只是看看这个代码会做什么,它会是什么样子。如果这让你感觉更好的话,我就用手把它全部打印出来。:p而不是复制和粘贴。
问题是你的缩进是错误的。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | from Tkinter import * import math class CircleArea(Frame): def __init__(self): """Sets up a window and widgets.""" Frame.__init__(self) self.master.title("Circle Area") self.grid() #Label and field for radius self._radiusLabel = Label(self, text ="Radius") self._radiusLabel.grid(row = 0, column = 0) self._radiusVar = DoubleVar() self._radiusEntry = Entry(self, textvariable = self._radiusVar) self._radiusEntry.grid(row = 0, column = 1) #Label and field for the area self._areaLabel = Label(self, text ="Area") self._areaLabel.grid(row = 1, column = 0) self._areaVar = DoubleVar() self._areaEntry = Entry(self, textvariable = self._areaVar) self._areaEntry.grid(row = 1, column = 1) # The command button self._button = Button(self, text ="Compute", command = self._area) self._button.grid(row = 2, column = 0, columnspan = 2) def _area(self): """Event handler for button.""" radius = self._radiusVar.get() area = radius ** 2 * math.pi self._areaVar.set(area) run = CircleArea() run.mainloop() |
实际上,我认为您在主方法中遗漏了一个参数,您定义了一个类CircleArea,但是在Python中,您知道,在类中定义的每个方法都必须有一个名为"self"的默认参数,所以只需尝试一下主(自):循环区域()主环()我想它会按你的意愿工作:)