我正在尝试基于tkinter构建计算器。我还将遵循there中的提示。 确定程序仍在进行中。由于这个错误,我目前陷入困境:
AttributeError:“ Calculator_GUI”对象没有属性“ main”
我不知道如何在两个班级之间进行沟通。我还要求对已经完成的工作进行简短回顾。提前致谢! 这是代码:
import tkinter as tk
from tkinter import ttk
class 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()
答案 0 :(得分:7)
在运行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()
的{{1}}和configure_input_space()
函数。