jeudi 11 mars 2021

How can I randomize the position of a button with Tkinter?

First post and still very new to python!

Basically I would like the buttons to be placed in random points of the root. I do not understand why they all stack in the middle, since I think I am placing them at random x and y

import tkinter as tk
from tkinter import *
from random import randint


num_buttons = int(input("How many buttons do you want?"))
buttons = [0] * num_buttons

root = tk.Tk()

canvas = tk.Canvas(root, height=700, width=700, bg="dark slate grey")
canvas.pack()

frame = tk.Frame(root, bg="red")
frame.place(relheight=0.6, relwidth=0.6, rely=0.2, relx=0.2) 


for k in range(num_buttons):
    randx = int(randint(-100,100))
    randy = int(randint(-100,100))
    buttons[k] = tk.Button(frame, text="DO NOT CLICK ME", 
                            fg="Black", highlightbackground="orange",
                            command=you_clicked)
    buttons[k].place(x=randx, y=randy)
    buttons[k].pack()

root.mainloop()

Thanks :)




Aucun commentaire:

Enregistrer un commentaire