使按钮在画布上工作(tkinter)

时间:2016-04-21 23:40:07

标签: python python-3.x tkinter tkinter-canvas

我试图让我的程序上的按钮执行操作,但我不是100%如何做到这一点。我已经创建了按钮,希望它们是正确的,但只需要一些关于如何使它们工作的建议!所以当我点击按钮"添加rect"它应该在随机位置添加一个随机矩形,反之亦然,以便删除。

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

1 个答案:

答案 0 :(得分:1)

您的代码需要进行严格的重组。

这是可以添加矩形的东西。你没有提供remove rectangle方法,所以我让你写出来 - 此时,delete button来电randomRect;你可能需要跟踪你在某种集合中创建的矩形,以便能够删除它们。

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