razorcode7 razorcode7 - 7 months ago 65
Python Question

Make buttons work on canvas (tkinter)

I'm trying to make the buttons on my program to perform an action but I'm not 100% how to do that. I've created the buttons hopefully their correct, but just need some advice on how to make them work ! so when i click the button "add rect" it should add a random rectangle in a random position vice versa for remove.

from tkinter import *
import random
root = Tk()

class Recta:

def __init__(self, height, width):
self.height=60
self.width=80
def randomRects(self,canvas):
w = random.randrange(80)
h = random.randrange(60)
canvas.create_rectangle(0,0,h,w,fill='green')

def create_buttons(self,canvas):
frame = Frame(root, bg='grey', width=400, height=40)
frame.pack(fill='x')
frame = Frame(root, bg='grey', width=400, height=40)
frame.pack(fill='x')
button1 = Button(frame, text='Add Rect')
button1.pack(side='left', padx=10)
button2 = Button(frame, text='Remove Rect')
button2.pack(side='left')

def removeRects(self,canvas):
self.myRect = canvas.create_rectangle(0, 0, w, h, fill='green')
canvas.delete(self.myRect)

c = Canvas(root)
c.pack()

tes = Recta(10,20)
tes.randomRects(c)
tes.create_buttons(1)
root.mainloop()

Answer

Your code needed serious reorganization.

Here is something that works to add rectangles. you did not provide a remove rectangle method, so i let you write it - at this moment, the delete button calls randomRect; you likely will need to keep track of the rectangles you create in a collection of some sort in order to be able to remove them.

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 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.randomRects)
        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()