[英]How can I randomize the position of a button with Tkinter?
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
我不明白为什么它们都堆在中间,因为我认为我将它们随机放置在 x 和 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()
You should not be calling both place
and pack
.您不应该同时调用
place
和pack
。 Only one geometry manager can control a widget.只有一个几何管理器可以控制一个小部件。 When you call
pack
, any effect a previous call to place
is thrown away.当你调用
pack
时,之前调用place
的任何效果都会被丢弃。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.