So I'm creating a script to test tkinter, which is supposed to generate random rectangles on a canvas. Here is my script:
from Tkinter import *
import random
tk = Tk()
canvas = Canvas(tk, width=400, height=400)
canvas.pack()
Option = StringVar()
Option.set("None")
menu = OptionMenu(tk, Option,"None", "Colored Outlines", "Colored Fills")
menu.pack()
option = Option.get()
button = button = Button(tk, text="Generate", command="Generate")
button.pack()
colors = ['red', 'orange', 'yellow', 'green', 'blue', 'purple']
def random_rectangle(width, height):
x1 = random.randrange(width)
y1 = random.randrange(height)
x2 = x1 + random.randrange(width)
y2 = y1 + random.randrange(height)
canvas.create_rectangle(x1, y1, x2, y2)
def random_outline_rectangle(width, height):
x1 = random.randrange(width)
y1 = random.randrange(height)
x2 = x1 + random.randrange(width)
y2 = y1 + random.randrange(height)
color = random.choice(colors)
canvas.create_rectangle(x1, y1, x2, y2, outline = color)
def random_color_rectangle(width, height):
x1 = random.randrange(width)
y1 = random.randrange(height)
x2 = x1 + random.randrange(width)
y2 = y1 + random.randrange(height)
color = random.choice(colors)
canvas.create_rectangle(x1, y1, x2, y2, fill = color)
def Generate():
global option
if option == "None":
for x in range(0,100):
random_rectangle(400, 400)
elif option == "Colored Outlines":
for x in range(0,100):
random_outline_rectangle(400,400)
elif option == "Colored Fills":
for x in range(0,1000):
random_color_rectangle(400,400)
tk.mainloop()
So my code works perfecty without the generate button (If I remove def Generate:()) but when I run it with that, and press the button, it does nothing. Without, you must set the option by changing the code at Option.set(). I do not understand why pressing the button does nothing, however, with the original code. Any help? And how can I fix this?
Ok, I found my solution. Rawing was right, but I also needed to move the button creation to after I defined all my functions. The updated code is as follows:
from Tkinter import *
import random
tk = Tk()
canvas = Canvas(tk, width=400, height=400)
canvas.pack()
Option = StringVar()
Option.set("None")
menu = OptionMenu(tk, Option,"None", "Colored Outlines", "Colored Fills")
menu.pack()
colors = ['red', 'orange', 'yellow', 'green', 'blue', 'purple']
def random_rectangle(width, height):
x1 = random.randrange(width)
y1 = random.randrange(height)
x2 = x1 + random.randrange(width)
y2 = y1 + random.randrange(height)
canvas.create_rectangle(x1, y1, x2, y2)
def random_outline_rectangle(width, height):
x1 = random.randrange(width)
y1 = random.randrange(height)
x2 = x1 + random.randrange(width)
y2 = y1 + random.randrange(height)
color = random.choice(colors)
canvas.create_rectangle(x1, y1, x2, y2, outline=color)
def random_color_rectangle(width, height):
x1 = random.randrange(width)
y1 = random.randrange(height)
x2 = x1 + random.randrange(width)
y2 = y1 + random.randrange(height)
color = random.choice(colors)
canvas.create_rectangle(x1, y1, x2, y2, fill=color, outline=color)
def Generate():
global option
canvas.delete("all")
if Option.get() == "None":
for x in range(0,100):
random_rectangle(400, 400)
elif Option.get() == "Colored Outlines":
for x in range(0,100):
random_outline_rectangle(400,400)
elif Option.get() == "Colored Fills":
for x in range(0,1000):
random_color_rectangle(400,400)
button = button = Button(tk, text="Generate", command=Generate)
button.pack()
tk.mainloop()
Related
I have a tool to capture screenshots but this tool only captures screenshots when you hold button-1 and move to the right side, when you hold button-1 and move it to the left side or up, it does not capture the screenshot, what is the reason and how can I fix it? I thought about it, but I think it's a mathematical problem, I'm waiting for your help.
import tkinter as tk
from PIL import Image, ImageTk, ImageGrab, ImageEnhance
root = tk.Tk()
root.resizable(0, 0)
def show_image(image):
win = tk.Toplevel()
win.image = ImageTk.PhotoImage(image)
tk.Label(win, image=win.image).pack()
win.grab_set()
win.wait_window(win)
def area_sel():
x1 = y1 = x2 = y2 = 0
roi_image = None
def on_mouse_down(event):
nonlocal x1, y1
x1, y1 = event.x, event.y
canvas.create_rectangle(x1, y1, x1, y1, outline='red', tag='roi')
def button_release(event):
print("ok")
win.destroy()
def on_mouse_move(event):
nonlocal roi_image, x2, y2
x2, y2 = event.x, event.y
canvas.delete('roi-image') # remove old overlay image
canvas.update()
roi_image = image.crop((x1, y1, x2, y2)) # get the image of selected region
canvas.image = ImageTk.PhotoImage(roi_image)
canvas.create_image(x1, y1, image=canvas.image, tag=('roi-image'), anchor='nw')
canvas.coords('roi', x1, y1, x2, y2)
# make sure the select rectangle is on top of the overlay image
canvas.lift('roi')
root.withdraw() # hide the root window
image = ImageGrab.grab() # grab the fullscreen as select region background
bgimage = ImageEnhance.Brightness(image).enhance(0.3) # darken the capture image
# create a fullscreen window to perform the select region action
win = tk.Toplevel()
win.attributes('-fullscreen', 1)
win.attributes('-topmost', 1)
canvas = tk.Canvas(win, highlightthickness=0)
canvas.pack(fill='both', expand=1)
tkimage = ImageTk.PhotoImage(bgimage)
canvas.create_image(0, 0, image=tkimage, anchor='nw', tag='images')
# bind the mouse events for selecting region
win.bind('<ButtonPress-1>', on_mouse_down)
win.bind('<ButtonRelease>', button_release)
win.bind('<B1-Motion>', on_mouse_move)
# use Esc key to abort the capture
win.bind('<Escape>', lambda e: win.destroy())
# make the capture window modal
win.focus_force()
win.grab_set()
win.wait_window(win)
root.deiconify() # restore root window
# show the capture image
if roi_image:
show_image(roi_image)
tk.Button(root, text='select area', width=30, command=area_sel).pack()
root.mainloop()
You need to keep x1 <= x2 and y1 <= y2 when cropping image and creating the roi rectangle:
def normalize(x1, y1, x2, y2):
if x1 > x2:
x1, x2 = x2, x1
if y1 > y2:
y1, y2 = y2, y1
return x1, y1, x2, y2
def on_mouse_move(event):
nonlocal roi_image, x2, y2
x2, y2 = event.x, event.y
rect = normalize(x1, y1, x2, y2)
canvas.delete('roi-image') # remove old overlay image
roi_image = image.crop(rect) # get the image of selected region
canvas.image = ImageTk.PhotoImage(roi_image)
canvas.create_image(rect[:2], image=canvas.image, tag=('roi-image'), anchor='nw')
canvas.coords('roi', rect)
# make sure the select rectangle is on top of the overlay image
canvas.lift('roi')
I have made a tkinter window which is round in shape.
I am trying to resize the window.
Everything works fine, but when I try to move it, it becomes square again.
I have added the code to draw the shape again, but still it becomes squared.
Here's the code:
from tkinter import Label, Tk, Canvas, BOTH, PhotoImage, Toplevel
from tkinter.constants import BOTTOM, E, NW, RAISED
import pyautogui as pg
root = Tk()
root.overrideredirect(1)
root.attributes("-transparentcolor", 'white')
root.attributes("-topmost", 1)
root.geometry("500x500")
# Creating a canvas for placing the squircle shape.
canvas = Canvas(root, height=500, width=500, highlightthickness=0, bg='white')
canvas.pack(fill=BOTH, expand=1)
def place_center(): # Placing the window in the center of the screen
global x, y
reso = pg.size()
rx = reso[0]
ry = reso[1]
x = int((rx/2) - (500/2))
y = int((ry/2) - (500/2))
root.geometry(f"500x500+{x}+{y}")
def move(event):
global rect
fx = root.winfo_pointerx() - 250
fy = root.winfo_pointery() - 10
root.geometry(f"500x500+{fx}+{fy}")
# if fx > 1 and fy > 1:
# canvas.delete(rect)
# rect = round_rectangle(0, 0, fx, fy, radius=50, fill="#1fa5fe")
def round_rectangle(x1, y1, x2, y2, radius=25, **kwargs): # Creating a rounded rectangle
points = [x1+radius, y1,
x1+radius, y1,
x2-radius, y1,
x2-radius, y1,
x2, y1,
x2, y1+radius,
x2, y1+radius,
x2, y2-radius,
x2, y2-radius,
x2, y2,
x2-radius, y2,
x2-radius, y2,
x1+radius, y2,
x1+radius, y2,
x1, y2,
x1, y2-radius,
x1, y2-radius,
x1, y1+radius,
x1, y1+radius,
x1, y1]
return canvas.create_polygon(points, **kwargs, smooth=True)
def cl(event):
root.quit()
def resize(event):
def end(event):
global rect
root.bind("<B1-Motion>", move)
global rect
global x, y
root.unbind("<B1-Motion>")
x = root.winfo_pointerx() - root.winfo_rootx()
y = root.winfo_pointery() - root.winfo_rooty()
if x > 0:
fx = root.winfo_rootx()
fy = root.winfo_rooty() + y
ht = root.winfo_height() - y
if ht > 0:
root.geometry(f"{x}x{ht}+{fx}+{fy}")
canvas.delete(rect)
rect = round_rectangle(0, 0, x, ht, radius=50, fill="#1fa5fe")
root.bind("<ButtonRelease-1>", end)
place_center()
# Creating the squircle
rect = round_rectangle(0, 0, 500, 500, radius=50, fill="#1fa5fe")
root.bind("<B1-Motion>", move)
root.bind("<Button-3>", cl)
rx = root.winfo_rootx()
ry = root.winfo_rooty()
side = Label(canvas, text=' \n', background="blue")
side.place(x=500-10, y=500-10)
side.bind("<B1-Motion>", resize)
root.unbind("<B1-Motion>")
root.mainloop()
Here're some images.
Before resizing:
After resizing and moving:
If you need, I am using Windows 10.
PS: Sorry if the code isn't written in good manner! I am creating this as a sample, which I will apply in my other apps when done.
Thank you.
NVM, I solved the problem.
When I was moving the window, it was set to default geometry, which made it look round.
I have changed it and here's the updated code for the move() function:
def move(event):
global rect
fx = root.winfo_pointerx() - 250
fy = root.winfo_pointery() - 10
try:
root.geometry(f"{x}x{ht}+{fx}+{fy}")
except Exception:
root.geometry(f"500x500+{fx}+{fy}")
The final code (with a few changes):
from tkinter import Label, Tk, Canvas, BOTH, PhotoImage, Toplevel
from tkinter.constants import BOTTOM, E, NW, RAISED, TOP
root = Tk()
root.overrideredirect(1)
root.attributes("-transparentcolor", 'white')
root.attributes("-topmost", 1)
root.geometry("500x500")
# Creating a canvas for placing the squircle shape.
canvas = Canvas(root, height=500, width=500, highlightthickness=0, bg='white')
canvas.pack(fill=BOTH, expand=1)
def place_center(): # Placing the window in the center of the screen
global x, y
rx = root.winfo_screenwidth()
ry = root.winfo_screenheight()
x = int((rx/2) - (500/2))
y = int((ry/2) - (500/2))
root.geometry(f"500x500+{x}+{y}")
def move(event):
global rect
fx = root.winfo_pointerx() - 250
fy = root.winfo_pointery() - 10
try:
root.geometry(f"{x}x{ht}+{fx}+{fy}")
except Exception:
root.geometry(f"500x500+{fx}+{fy}")
# if fx > 1 and fy > 1:
# canvas.delete(rect)
# rect = round_rectangle(0, 0, fx, fy, radius=50, fill="#1fa5fe")
def round_rectangle(x1, y1, x2, y2, radius=25, **kwargs): # Creating a rounded rectangle
points = [x1+radius, y1,
x1+radius, y1,
x2-radius, y1,
x2-radius, y1,
x2, y1,
x2, y1+radius,
x2, y1+radius,
x2, y2-radius,
x2, y2-radius,
x2, y2,
x2-radius, y2,
x2-radius, y2,
x1+radius, y2,
x1+radius, y2,
x1, y2,
x1, y2-radius,
x1, y2-radius,
x1, y1+radius,
x1, y1+radius,
x1, y1]
return canvas.create_polygon(points, **kwargs, smooth=True)
def cl(event):
root.quit()
def resize(event):
global rect
global x, y, ht
x = root.winfo_pointerx() - root.winfo_rootx()
y = root.winfo_pointery() - root.winfo_rooty()
if x > 0:
fx = root.winfo_rootx()
fy = root.winfo_rooty() + y
ht = root.winfo_height() - y
if ht > 0:
root.geometry(f"{x}x{ht}+{fx}+{fy}")
canvas.delete(rect)
rect = round_rectangle(0, 0, x, ht, radius=50, fill="#1fa5fe")
place_center()
top = Canvas(canvas, height=50, bg="#1fa5fe", highlightthickness=0)
top.pack(side=TOP, pady=2)
# Creating the squircle
rect = round_rectangle(0, 0, 500, 500, radius=50, fill="#1fa5fe")
top.bind("<B1-Motion>", move)
root.bind("<Button-3>", cl)
rx = root.winfo_rootx()
ry = root.winfo_rooty()
side = Label(canvas, text=' \n', background="blue")
side.place(x=500-10, y=500-10)
side.bind("<B1-Motion>", resize)
root.unbind("<B1-Motion>")
root.mainloop()
Thanks to lots of help in Drag and drop the object in Tkinter UI, I could manage to draw three square that are draggable.
Now I am trying to draw 3 lines between each squares and I cannot find way to enable it. What I tried is following :
from tkinter import *
window = Tk()
window.state('zoomed')
window.configure(bg = 'white')
def drag(event):
new_x = event.x_root - window.winfo_rootx()
new_y = event.y_root - window.winfo_rooty()
event.widget.place(x=new_x, y=new_y,anchor=CENTER)
card = Canvas(window, width=10, height=10, bg='red1')
card.place(x=300, y=600,anchor=CENTER)
card.bind("<B1-Motion>", drag)
another_card = Canvas(window, width=10, height=10, bg='red2')
another_card.place(x=600, y=600,anchor=CENTER)
another_card.bind("<B1-Motion>", drag)
third_card = Canvas(window, width=10, height=10, bg='red3')
third_card.place(x=600, y=600,anchor=CENTER)
third_card.bind("<B1-Motion>", drag)
def line(x1, y1, x2, y2):
print(x1, y1, x2, y2)
Canvas.create_line(x1, y1, x2, y2, fill="green")
coor_1 = canvas.coords(card)
coor_2 = canvas.coords(another_card)
line(coor_1[0],coor_1[1],coor_1[0],coor_2[1])
window.mainloop()
It didn't work and I don't think it will work since this code does not catch the change occurred by dragging object, But I cannot guess how to code since I do not understand how the event function works completely. How should I make a code for it ?
for the purpose of self-study:
import tkinter as tk
window = tk.Tk()
window.state('zoomed')
class DragAndDropArea(tk.Canvas):
def __init__(self,master, **kwargs):
tk.Canvas.__init__(self,master, **kwargs)
self.active = None
card_I = self.draw_card(300,600, 100,100, 'red1')
card_II = self.draw_card(600,600, 100,100, 'red2')
card_III = self.draw_card(400,400, 100,100, 'red3')
self.bind_tention(card_I,card_III)
self.bind_tention(card_I,card_II)
self.bind_tention(card_III,card_II)
self.bind('<ButtonPress-1>', self.get_item)
self.bind('<B1-Motion>',self.move_active)
self.bind('<ButtonRelease-1>', self.set_none)
def set_none(self,event):
self.active = None
def get_item(self,event):
try:
item = self.find_withtag('current')
self.active = item[0]
except IndexError:
print('no item was clicked')
def move_active(self,event):
if self.active != None:
coords = self.coords(self.active)
width = coords[2] - coords[0] #x2-x1
height= coords[1] - coords[3] #y1-y2
position = coords[0],coords[1]#x1,y1
x1 = event.x - width/2
y1 = event.y - height/2
x2 = event.x + width/2
y2 = event.y + height/2
self.coords(self.active, x1,y1, x2,y2)
try:
self.update_tention(self.active)
except IndexError:
print('no tentions found')
def update_tention(self, tag):
tentions = self.find_withtag(f'card {tag}')
for tention in tentions:
bounded_cards = self.gettags(tention)
card = bounded_cards[0].split()[-1]
card2= bounded_cards[1].split()[-1]
x1,y1 = self.get_mid_point(card)
x2,y2 = self.get_mid_point(card2)
self.coords(tention, x1,y1, x2,y2)
self.lower(tention)
def draw_card(self, x,y, width,height, color):
x1,y1 = x,y
x2,y2 = x+width,y+height
reference = self.create_rectangle(x1,y1,x2,y2,
fill = color)
return reference
def bind_tention(self, card, another_card):
x1,y1 = self.get_mid_point(card)
x2,y2 = self.get_mid_point(another_card)
tag_I = f'card {card}'
tag_II= f'card {another_card}'
reference = self.create_line(x1,y1,x2,y2, fill='green',
tags=(tag_I,tag_II))
self.lower(reference)
def get_mid_point(self, card):
coords = self.coords(card)
width = coords[2] - coords[0] #x2-x1
height= coords[1] - coords[3] #y1-y2
position = coords[0],coords[1]#x1,y1
mid_x = position[0] + width/2
mid_y = position[1] - height/2
return mid_x,mid_y
area = DragAndDropArea(window, bg='white')
area.pack(fill='both',expand=1)
window.mainloop()
The following program draws a rectangle in the center of the canvas. The rectangle is supposed to get wider when the right arrow key is pressed, and narrower when the left arrow key is pressed.
Here's the code:
from tkinter import *
root = Tk()
canvas = Canvas(root, width=400, height=300, bg="#000000")
canvas.pack()
x1 = 150
y1 = 100
x2 = 250
y2 = 200
class ResizeRect:
def __init__(self, x1, y1, x2, y2):
self.x1 = x1
self.y1 = y1
self.x2 = x2
self.y2 = y2
self.rect = canvas.create_rectangle(0,0,1,1)
def draw(self):
canvas.delete(self.rect)
self.rect = canvas.create_rectangle(x1, y1, x2, y2,
outline="#00B000", width=2)
def narrower(self):
self.x1 = self.x1 + 5
self.x2 = self.x2 - 5
def wider(self):
self.x1 = self.x1 - 5
self.x2 = self.x2 + 5
r = ResizeRect(150, 100, 250, 200)
r.draw()
def left(event):
r.narrower()
r.draw()
def right(event):
r.wider()
r.draw()
canvas.bind_all('<KeyPress-Left>', left)
canvas.bind_all('<KeyPress-Right>', right)
My teacher told me that I need to add the 'self' keyword to the parameters in the draw function but I don't know what he means. (I can't ask him more because he's in a bad mood right now.). Any help is much appreciated.
I have a problem with my project. I want my class Baustein to be a blueprint of an object I can place in my Display in the gui_backup.py. The program launches and everything works, but as I click the left button (button1) the same program opens again and now I have 2 programs going separately but I have no new Object in the Display created, just the old one which is being created in gui_backup in blue, but I want to create one in red with the class Baustein from Bauklotz_class.py. Here are my codes:
Bauklotz_class.py
from gui_backup import Display
class Baustein:
x1, y1, x2, y2 = 10,10,20,20
color = "red"
def __init__(self, x1, y1, x2, y2, color):
self.x1 = x1
self.x2 = x2
self.y1 = y1
self.y2 = y2
self.color = color
def show_new_object(self):
quadrat2 = Display.create_rectangle(40, 50, 60, 70, fill = color)
Display.coords(quadrat2, 40, 50, 60, 70)
gui_backup.py
from tkinter import *
import curses
x1 = 10 #initialise coordinates
y1 = 10
x2 = 20
y2 = 20
root = Tk() #create window
root.wm_title("Raspberry Pi GUI") #window title
root.config(background = "#FFFFFF") #background color
#The whole left frame and widgets involved
leftFrame = Frame(root, width=200, height = 400)
leftFrame.grid(row=0, column = 0, padx = 10, pady = 3)
leftLabel1 = Label(leftFrame, text = "Platzhalter Text")
leftLabel1.grid(row = 0, column = 0, padx = 10, pady = 3)
leftLabel2 = Label(leftFrame, text = "Dies ist ein Text\nmit mehreren Zeilen")
leftLabel2.grid(row = 1, column = 0, padx = 10, pady = 3)
#the whole right frame and widgets involved
rightFrame = Frame(root, width=400, height = 400)
rightFrame.grid(row = 0, column = 1, padx = 10, pady = 3)
E1 = Entry(rightFrame, width = 50)
E1.grid(row = 0, column = 0, padx = 10, pady = 60)
#The two functions for the 2 buttons created
def callback1():
import Bauklotz_class
test = Bauklotz_class.Baustein(20, 30, 40, 50, "red")
test.show_new_object()
def callback2():
print(1+1)
buttonFrame = Frame(rightFrame)
buttonFrame.grid(row = 1, column = 0, padx = 10, pady = 60)
B1 = Button(buttonFrame, text = "Button1", bg = "#FF0000", width = 15, command = callback1)
B1.grid(row = 0, column = 0, padx = 10, pady = 60)
B2 = Button(buttonFrame, text = "Button2", bg ="#FFFF00", width = 15, command = callback2)
B2.grid(row = 0, column = 1, padx = 10, pady = 60)
Slider = Scale(rightFrame, from_ = 0, to = 100, resolution = 0.1, orient = HORIZONTAL, length = 400)
Slider.grid(row = 2, column = 0, padx = 10, pady = 3)
Display = Canvas(rightFrame, width = 300, height = 300)
Display.configure(background = 'black')
Display.grid(row = 1, column = 3, padx = 10, pady = 3)
quadrat = Display.create_rectangle(20, 30, 40, 50, fill = "blue")
Display.coords(quadrat, x1, y1, x2, y2)
#following functions are for coordination of the square
#also you can find here the exceptions so that the object
#cant break out of the display widget
def down(event):
global x1, y1, x2, y2
if x2 == 290 or y2 == 300:
pass
else:
y1 += 10
y2 += 10
Display.coords(quadrat, x1, y1, x2, y2)
leftLabel1.config(text = "x1: " + str(x1) + ", x2:" + str(x2) + ", y1:" + str(y1) + ", y2:" + str(y2), width = "40" , )
def up(event):
global x1, y1, x2, y2
if x2 == 0 or y2 == 10:
pass
else:
y1 -= 10
y2 -= 10
Display.coords(quadrat, x1, y1, x2, y2)
leftLabel1.config(text = "x1: " + str(x1) + ", x2:" + str(x2) + ", y1:" + str(y1) + ", y2:" + str(y2), width = "40" , )
def left(event):
global x1, y1, x2, y2
if x1 == 0 or y1 == 10:
pass
else:
x1 -= 10
x2 -= 10
Display.coords(quadrat, x1, y1, x2, y2)
leftLabel1.config(text = "x1: " + str(x1) + ", x2:" + str(x2) + ", y1:" + str(y1) + ", y2:" + str(y2), width = "40" , )
def right(event):
global x1, y1, x2, y2
if x1 == 290 or y1 == 300:
pass
else:
x1 += 10
x2 += 10
Display.coords(quadrat, x1, y1, x2, y2)
leftLabel1.config(text = "x1: " + str(x1) + ", x2:" + str(x2) + ", y1:" + str(y1) + ", y2:" + str(y2), width = "40" , )
root.bind('<a>', left)
root.bind('<w>', up)
root.bind('<s>', down)
root.bind('<d>', right)
root.mainloop()
Here are also some screenshots for you to understand it better:
Does someone know why my project is duplicating itself?
The problem lies within your double import, i guess. You see, you import from gui_backup.py into Bauklotz_class.py, while also importing vice versa, which leads to weird and unexpected behaviour. Also, inside the definition of show_new_object, you should use self.color instead of color as an argument for Display.create_rectangle, because self.color is a class attribute and thus the proper object to use in a class method definition. One way to fix your Problem is to add an additional attribute, let's call it canvas, to Baustein, and removing the import Display, so Bauklotz_class.py now looks like this:
class Baustein():
x1, y1, x2, y2 = 10, 10, 20, 20
color = "red"
def __init__(self, x1, y1, x2, y2, color, canvas):
self.x1 = x1
self.x2 = x2
self.y1 = y1
self.y2 = y2
self.color = color
self.canvas=canvas
def show_new_object(self):
quadrat2 = self.canvas.create_rectangle(40, 50, 60, 70, fill=self.color)
self.canvas.coords(quadrat2, 40, 50, 60, 70)
And then call it like this in gui_backup.py:
...
def callback1():
import Bauklotz_class
test = Bauklotz_class.Baustein(20, 30, 40, 50, "red", Display)
test.show_new_object()
which will fix your problem, and create a red rectangle instead of duplicating your window.