screenshot tool not working to take screenshot of left side - python

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

Related

Creating a shape and adjusting the parameters of the shape in Tkinter

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

How to resize a tkinter overrideredirect window with a shape in it?

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

How to make a tkinter window rounded?

I am trying to make a tkinter overrideredirect window round in shape.
I've done this so far:
from tkinter import Tk, Canvas, BOTH, PhotoImage
from tkinter.constants import NW, RAISED
import pyautogui as pg
root = Tk()
root.overrideredirect(1)
root.attributes("-topmost", 1)
root.geometry("500x500")
# Creating a canvas for placing the squircle shape.
canvas = Canvas(root, height=500, width=500, highlightthickness=0)
canvas.pack()
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 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)
place_center()
# Taking a screenshot and adding it to the canvas to create a transparent effect
root.withdraw()
s = pg.screenshot(region=(x, y, 500, 500))
tp = "C:\\Users\\username\\AppData\\Local\\Temp\\bg.png"
s.save(tp)
bg = PhotoImage(file=tp)
canvas.create_image(0, 0, image=bg, anchor=NW)
root.deiconify()
os.remove(tp)
# Creating the squircle
round_rectangle(0, 0, 500, 500, radius=70, fill="#1fa5fe")
root.mainloop()
I use this function to move the window:
def move(event):
fx = root.winfo_pointerx() - 250
fy = root.winfo_pointery() - 10
root.geometry(f"500x500{fx}+{fy}")
I haven't added it into the code because when I move the window, it becomes square again as the screenshot is taken only of a particular region.
Before moving:
After moving:
How can I make it round even when I move it?
I tried using root.withdraw() and root.deiconify() in a while True: loop, but it causes flickering.
Any help would be appreciated.
Thank you.
how to change window's shape in tkinter (although this should work most certainly on Windows computers, some other OS (macOS, Linux) may have issues meaning that this exact code may not work and not give the desired output). Explanation in code comments:
from tkinter import Tk, Canvas
from PIL import Image, ImageTk
import requests
# load image from web but you can of course load it from file, this is
# just so you can run and immediately see the results
url = 'http://media-s3-us-east-1.ceros.com/g3-communications/images/2019/01/15/05eea4b9b9ce010d2dd6b0c063d2f5ca/p1-blob.png?imageOpt=1&fit=bounds&width=893'
data = requests.get(url, stream=True).raw
# just when loading your own image instead of `data` use the path, and resize
# if you need, can obvs change these numbers
image = Image.open(data).resize((600, 600), Image.ANTIALIAS)
root = Tk()
# set root bg color to some rare color because
# the `-transparentcolor` affects all colors on the window, all of them
root.config(bg='grey15')
# just simply set window to the middle, not necessary
root.geometry(f'+{root.winfo_screenwidth() // 2 - 300}+{root.winfo_screenheight() // 2 - 300}')
# the important part, set the transparentcolor to some rare color in this case `grey15`,
# can obvs be sth else depending on your theme
root.attributes('-transparentcolor', 'grey15')
# remove window from window manager
root.overrideredirect(True)
# create canvas and set the bg to the same "rare" color (width and height set
# to image width and height, can be sth different too)
canvas = Canvas(
root, bg='grey15', width=image.width, height=image.height, highlightthickness=0
)
canvas.pack()
# convert image to PhotoImage for `tkinter` to understand
photo = ImageTk.PhotoImage(image)
# put the image on canvas because canvas supports transparent bg
canvas.create_image(0, 0, image=photo, anchor='nw')
root.mainloop()
The key parts are .attributes('-transparentcolor', ...) (which is the most likely to not work on some OS) and that the shape of the window is formed by an image of that shape (the image should have transparent background (a .png image)). It is also possible to simply draw a shape using Canvas methods (.create_). Also important to remember that the attribute affects all the colors on the window meaning that for example if you were to set the transparentcolor to say white and your background image contained white, it will most likely be transparent too (tho probably won't look as good) so I would suggest using some color that is the least likely to be on the GUI
I believe this will solve your problem.
from tkinter import *
from PIL import ImageTk, Image
import pyautogui as pg
root = Tk()
root.overrideredirect(1)
root.configure(bg="white")
root.attributes("-topmost", 1)
root.attributes("-transparentcolor", "white")
root.geometry("500x500")
label = Label(root, height=900, width=900, bg="white", border=0)
label.pack()
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}")
place_center()
img = Image.open("bg.png")
img = img.resize((300, 300), Image.ANTIALIAS)
imagem = ImageTk.PhotoImage(img)
label.configure(image=imagem)
root.mainloop()

Calculating disctance between 2 coordinates using click events

I can display an image on my panel, what I need is to click on 2 spots in the picture and calculate the distance between them. I am having trouble with the event handler and how to use it similarly to a scanner in Java. For example, if I run the program and click once somewhere in the image, it runs all 3 methods at once which leads to give an error.
root = Tk()
img = ImageTk.PhotoImage(Image.open("target.PNG"))
#img = cv2.imread("target.PNG")
panel = Label(root, image = img)
panel.pack(side = "bottom", fill = "both", expand = "yes")
def leftClick(event):
global x0,y0
x0 = event.x
y0 = event.y
return x0, y0
panel.bind("<Button-1>", leftClick)
def rightClick(event):
global x1,y1
x1 = event.x
y1 = event.y
return x1, y1
panel.bind("<Button-1>", rightClick)
def getDistance(event):
distance = math.sqrt( ((x0-x1)**2)+((y0-y1)**2) )
print(distance)
panel.bind("<Button-1>", getDistance)
root.mainloop()
What I'm looking for is to execute each step once at a time. The final step to calculate the distance can be done outside a method it doesn't really matter. I just need to get the coordinates to work first. Please let me know how I could proceed to solve this.
You Can Try This Two:
Process 1(Uses mouse left click, right click, middle(scroll) click):
The following code takes
(x0, y0) from mouse-left-click
(x1, y1) from mouse-right-click
and then prints distance between them on mouse-middle(scroll)-click
from tkinter import *
from PIL import ImageTk, Image
import math
root = Tk()
img = ImageTk.PhotoImage(Image.open("Logo.png"))
panel = Label(root, image=img)
panel.pack(side="bottom", fill="both", expand="yes")
x0 = 0
y0 = 0
x1 = 0
y1 = 0
def leftClick(event):
global x0, y0
x0 = event.x
y0 = event.y
# return [x0, y0]
panel.bind("<Button-1>", leftClick)
def rightClick(event):
global x1, y1
x1 = event.x
y1 = event.y
# return x1, y1
panel.bind("<Button-3>", rightClick)
def getDistance(event):
global x0, y0, x1, y1
distance = math.sqrt(((x0 - x1)**2)+((y0 - y1)**2))
print(distance)
panel.bind("<Button-2>", getDistance)
root.mainloop()
Process 2(Uses only mouse left click):
The following code takes
(x0, y0) from first mouse-left-click
(x1, y1) from second mouse-left-click
and then prints distance between them on third mouse-left-click
from tkinter import *
from PIL import ImageTk, Image
import math
root = Tk()
img = ImageTk.PhotoImage(Image.open("Logo.png"))
panel = Label(root, image=img)
panel.pack(side="bottom", fill="both", expand="yes")
counter = 0
x0 = 0
x1 = 0
y0 = 0
y1 = 0
def getDistance(event):
global counter, x0, y0, x1, y1
if counter == 0:
x0 = event.x
y0 = event.y
counter += 1
elif counter == 1:
x1 = event.x
y1 = event.y
counter += 1
elif counter == 2:
distance = math.sqrt(((x0 - x1)**2)+((y0 - y1)**2))
print(distance)
counter = 0
panel.bind("<Button-1>", getDistance)
root.mainloop()
Below is a demo for count distance from a start point to a end point, which takes a DRAG operation with mouse left button.
import tkinter as tk
from PIL import ImageTk, Image
import math
start_point_x, start_point_y, end_point_x, end_point_y = 0, 0, 0, 0
def mouse_left_down_detection(event):
global start_point_x, start_point_y
start_point_x = event.x
start_point_y = event.y
def mouse_left_release_detection(event):
global end_point_x, end_point_y
end_point_x = event.x
end_point_y = event.y
print(start_point_x, start_point_y, end_point_x, end_point_y)
print(get_instance(start_point_x, start_point_y, end_point_x, end_point_y))
def get_instance(x1, y1, x2, y2):
return math.sqrt((pow(abs(x2-x1), abs(x2-x1))+pow(abs(y2-y1), abs(y2-y1))))
image_path = "andy.jpg"
root = tk.Tk()
img = ImageTk.PhotoImage(Image.open(image_path))
panel = tk.Label(root, image=img)
# Bind event mouse left down
panel.bind("<Button-1>", mouse_left_down_detection)
# Bind event mouse left release and calculate distance
panel.bind("<ButtonRelease-1>", mouse_left_release_detection)
panel.pack(side="bottom", fill="both", expand="yes")
root.mainloop()

Script not working (Tkinter and Functions)

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

Categories