我正在尝试使用我的画布上的OnButtonAddClick函数在类mainWindow中打印一个矩形,但是当我尝试获取错误时: AttributeError:' NoneType'对象没有属性' create_rectangle'
这是关于OnButtonAddClick的功能,但我看不出有什么问题。我现在尝试了几件事,希望你能帮助我。
import tkinter as tk
import Calc as c
class mainWindow(tk.Frame):
def __init__(self, master):
tk.Frame.__init__(self, master)
self.master = master
self.Canvas()
#more stuff
def button(self):
self.buttonAdd = tk.Button(self, text='Add', width=12, command=self.OnButtonAddClick).grid(column=2, row=10)
##more stuff
def Canvas(self):
"Projecting elements on canvas"
self.canvas = tk.Canvas(self, width=500, height=500, borderwidth=20, bg='white').grid(column=5, row=2, rowspan=30)
def OnButtonAddClick(self):
self.canvas.create_rectangle(200,200,200,200)
print('hi')
if __name__ == '__main__':
root = tk.Tk()
mainWindow(root).pack(side='top', fill='both')
root.mainloop()
答案 0 :(得分:0)
从初始化调用中分离布局调用:
self.buttonAdd = tk.Button(...).grid(...)
...
self.canvas = tk.Canvas(...).grid(...)
为:
self.buttonAdd = tk.Button(...)
self.buttonAdd.grid(...)
...
self.canvas = tk.Canvas(...)
self.canvas.grid(...)