单击"删除rect"尝试在画布上删除随机形状。按钮创建。但我的方法似乎不起作用。我不断收到这个错误,必须很小但我似乎无法找到它。
TypeError:removeRects()缺少1个必需的位置参数:' canvas'
from tkinter import *
import random
root = Tk()
class Recta:
def __init__(self, height=60, width=80):
self.height = height
self.width = width
self.create_buttons()
self.canvas = Canvas(root)
self.canvas.pack()
def removeRects(self,canvas):
my_rect = self.canvas.create_rectangle(0,0,w,h,fill = "green")
self.canvas.delete(my_rect)
def create_buttons(self):
self.frame = Frame(root, bg='grey', width=400, height=40)
self.frame.pack(fill='x')
self.button1 = Button(self.frame, text='Rect', command=self.randomRects)
self.button1.pack(side='left', padx=10)
self.button2 = Button(self.frame, text='Remove Rect', command=self.removeRects)
self.button2.pack(side='left')
def randomRects(self):
w = random.randrange(300)
h = random.randrange(200)
self.canvas.create_rectangle(0, 0, w, h, fill= "green")
tes = Recta()
root.mainloop()
答案 0 :(得分:0)
您必须跟踪您在集合中创建的矩形;然后从集合中提取id
以删除矩形。
在这里,我创建了一个列表来聚合创建的矩形的id:self.canvas.create_rectangle(0, 0, w, h, fill='green')
返回存储在集合中的id号。
调用delete
方法后,将检索上一个创建的矩形中的id
(并从集合中删除)并用于remove
中canvas
的矩形
import tkinter as tk
import random
root = tk.Tk()
class Recta:
def __init__(self, height=60, width=80):
self.height = height
self.width = width
self.create_buttons()
self.canvas = tk.Canvas(root)
self.canvas.pack()
self.rects = []
def create_buttons(self):
self.frame = tk.Frame(root, bg='grey', width=400, height=40)
self.frame.pack(fill='x')
self.button1 = tk.Button(self.frame, text='Add Rect', command=self.randomRects)
self.button1.pack(side='left', padx=10)
self.button2 = tk.Button(self.frame, text='Remove Rect', command=self.removeRects)
self.button2.pack(side='left')
def removeRects(self):
if len(self.rects) > 0:
self.canvas.delete(self.rects.pop())
def randomRects(self):
w = random.randrange(300)
h = random.randrange(200)
self.rects.append(self.canvas.create_rectangle(0, 0, w, h, fill='green'))
tes = Recta()
root.mainloop()
以下是与* import相同的代码!
from tkinter import *
import random
root = Tk()
class Recta:
def __init__(self, height=60, width=80):
self.height = height
self.width = width
self.create_buttons()
self.canvas = Canvas(root)
self.canvas.pack()
self.rects = []
def create_buttons(self):
self.frame = Frame(root, bg='grey', width=400, height=40)
self.frame.pack(fill='x')
self.button1 = Button(self.frame, text='Add Rect', command=self.randomRects)
self.button1.pack(side='left', padx=10)
self.button2 = Button(self.frame, text='Remove Rect', command=self.removeRects)
self.button2.pack(side='left')
def removeRects(self):
if len(self.rects) > 0:
self.canvas.delete(self.rects.pop())
def randomRects(self):
w = random.randrange(300)
h = random.randrange(200)
self.rects.append(self.canvas.create_rectangle(0, 0, w, h, fill='green'))
tes = Recta()
root.mainloop()