我正在尝试基于 tkinter 构建计算器。我也遵循那里的提示。程序肯定还在进行中。由于此错误,我目前陷入困境:AttributeError: 'Calculator_GUI' 对象没有属性 'main'我不知道如何在两个班级之间进行工作交流。我还要求对已经完成的工作进行简短审查。提前致谢!这是代码:import tkinter as tkfrom tkinter import ttkclass Calculator_Core(): def __init__(self): self.input = tk.StringVar() def buttonClick(self, a): self.input.set(a) #DEBUG: print(self.input)class Calculator_GUI(tk.Frame): def __init__(self, master): tk.Frame.__init__(self, master) self.master = master self.button = {} self.configure_gui() self.create_widgets() self.main = Calculator_Core() def configure_gui(self): self.master.title("Calculator") self.master.resizable(False, False) def create_widgets(self): self.configure_input_space() row_number = 1 column_number = 0 a = -1 text_buttons = ('789+', '456-', '123*', '0=/C') for button_row in text_buttons: for text_button in button_row: a += 1 self.configure_button(text_button, row_number, column_number, a) column_number += 1 row_number += 1 column_number = 0 def configure_button(self, text, row, column, key): self.button[key] = ttk.Button(self.master, text=text, command=lambda: self.main.buttonClick(text)) self.button[key].grid(row=row, column=column) def configure_input_space(self): self.entry = ttk.Entry(self.master, textvariable=self.main.input) self.entry.grid(columnspan=4, sticky='we')if __name__ == "__main__": root = tk.Tk() Calculator_GUI(root) root.mainloop()
1 回答
万千封印
TA贡献1891条经验 获得超3个赞
您需要self.main在运行该create_widgets()功能之前“制作” ,因此:
class Calculator_GUI(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
self.master = master
self.button = {}
self.configure_gui()
self.create_widgets()
self.main = Calculator_Core()
应该是这样的:
class Calculator_GUI(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
self.master = master
self.main = Calculator_Core()
self.button = {}
self.configure_gui()
self.create_widgets()
因为该create_widgets()函数运行了configure_button()和configure_input_space()引用了 的函数self.main。
添加回答
举报
0/150
提交
取消