Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
321 views
in Technique[技术] by (71.8m points)

Can I create random x and y coordinates for a button - Tkinter Python

import tkinter as tk 
import random

root = tk.Tk() 

canvas = tk.Canvas(root, height=600, width=700, bg="#4f75b3")
canvas.pack()

frame = tk.Frame(root, bg="#66bd5e")
frame.place(relx=0.075, rely=0.075, relheight=0.85, relwidth=0.85,)

def destroymole():
    mole.destroy()

mole = tk.Button(root,text="MOLE", relief="raised", command=destroymole, x=random.randint(300,700), y=random.randint(300, 700), height=20, width=30)

root.mainloop()

After running this I get this error

Traceback (most recent call last):   File
"C:Users\PycharmProjectspythonProjectGUI APP.py", line 15, in
<module>
    mole = tk.Button(root, text="MOLE",relief="raised", command=destroymole, x=random.randint(300,700),y=random.randint(300,
700), height=20, width=30)   File
"C:Users\AppDataLocalProgramsPythonPython39libkinter\__init__.py",
line 2647, in __init__
    Widget.__init__(self, master, 'button', cnf, kw)   File "C:Users\AppDataLocalProgramsPythonPython39libkinter\__init__.py",
line 2569, in __init__
    self.tk.call(
_tkinter.TclError: unknown option "-x"

However, the main one is the last line and I'm pretty sure it is to do with the random number

If there are any other apparent issues then please tell me because this is all a mystery to me.

question from:https://stackoverflow.com/questions/65916269/can-i-create-random-x-and-y-coordinates-for-a-button-tkinter-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You have not placed the button. Hope, you know that there are three ways by which you can set up the widget in the window (place, pack, grid). I have used the place method and passed the random value in the parameter.

import tkinter as tk 
import random

root = tk.Tk() 

canvas = tk.Canvas(root, height=600, width=700, bg="#4f75b3")
canvas.pack()

frame = tk.Frame(root, bg="#66bd5e")
frame.place(relx=0.075, rely=0.075, relheight=0.85, relwidth=0.85,)

def destroymole():
    mole.destroy()

mole = tk.Button(root,text="MOLE", relief="raised", command=destroymole)
mole.place(x=random.randint(300,700), y=random.randint(300, 700), height=20, width=30)

root.mainloop()

Rest for any query feel free to ask me.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...