Home > Mobile >  Creating a shape and adjusting the parameters of the shape in Tkinter
Creating a shape and adjusting the parameters of the shape in Tkinter

Time:03-11

I want to create a rectangle with a checkbutton on a canvas, and then having sliders to adjust the height and width of this rectangle, but it seems that the rectangle I create does not carry over to the other functions, as I just create the triangle, and when adjusting the height and width, nothing happens.

from tkinter import *

def rect():
    rectangle = canvas.create_rectangle(20,50, 40, 10, fill="green")

def width(e, rectangle):
    x0, y0, x1, y1 = canvas.coords(rectangle) # get the coords of rect
    x1 = float(e)                             # calc new coords
    canvas.coords(rectangle, x0, y0, x1, y1)  # set new coords

def height(h, rectangle):
    x0, y0, x1, y1 = canvas.coords(rectangle)
    y1 = float(h)   40
    canvas.coords(rectangle, x0,y0,x1,y1)

root = Tk()
frame = Frame(root)
frame.pack()

create_rect = Checkbutton(frame, text='rect', variable=IntVar, command = rect)
create_rect.pack()
slider = Scale(frame, from_=10 , to=100, orient = HORIZONTAL, bg="blue",command = width)
slider.pack()
slider = Scale(frame, from_=10 , to=100, orient = HORIZONTAL, bg="green",command = height)
slider.pack()
canvas = Canvas(root,height=500,width=360)
canvas.pack()

root.mainloop()

CodePudding user response:

In order to access rectangle outside rect(), you can make it a global variable. Below is the modified code:

from tkinter import *

rectangle = None  # initialize rectangle

def rect():
    # tell Python rectangle is a global variable
    global rectangle
    if cbvar.get() == 1:
        # create the rectangle if checkbutton is checked
        if rectangle is None:
            rectangle = canvas.create_rectangle(20, 10, 20 wslider.get(), 10 hslider.get(), fill="green")
    else:
        # destroy the rectangle if checkbutton is not checked
        if rectangle:
            canvas.delete(rectangle)
            rectangle = None

def width(e):
    # make sure rectangle exists
    if rectangle:
        x0, y0, x1, y1 = canvas.coords(rectangle) # get the coords of rect
        x1 = x0   float(e)                        # calc new coords
        canvas.coords(rectangle, x0, y0, x1, y1)  # set new coords

def height(h):
    # make sure rectangle exists
    if rectangle:
        x0, y0, x1, y1 = canvas.coords(rectangle)
        y1 = y0   float(h)
        canvas.coords(rectangle, x0, y0, x1, y1)

root = Tk()
frame = Frame(root)
frame.pack()

cbvar = IntVar()
create_rect = Checkbutton(frame, text='rect', variable=cbvar, command=rect)
create_rect.pack()
wslider = Scale(frame, from_=10 , to=100, orient = HORIZONTAL, bg="blue", command=width)
wslider.pack()
hslider = Scale(frame, from_=10 , to=100, orient = HORIZONTAL, bg="green", command=height)
hslider.pack()
canvas = Canvas(root, height=500, width=360)
canvas.pack()

root.mainloop()
  • Related