python - 我可以为按钮创建随机 x 和 y 坐标 - 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()
运行后我得到这个错误
Traceback (most recent call last): File
"C:\Users\\PycharmProjects\pythonProject\GUI 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\\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py",
line 2647, in __init__
Widget.__init__(self, master, 'button', cnf, kw) File "C:\Users\\AppData\Local\Programs\Python\Python39\lib\tkinter\__init__.py",
line 2569, in __init__
self.tk.call(
_tkinter.TclError: unknown option "-x"
但是,主要的是最后一行,我很确定它与随机数有关
如果还有其他明显的问题,请告诉我,因为这对我来说都是一个谜。
解决方案
您尚未放置按钮。希望,您知道可以通过三种方式在窗口中设置小部件(放置、包装、网格)。我使用了place方法并在参数中传递了随机值。
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()
如有任何疑问,请随时问我。
推荐阅读
- go - 如何通过 utc 偏移量加载位置
- php - 在 PHP 中使用数组制作参数化 SELECT 查询
- python - Yolo Darkflow error. tensorflow.python.framework.errors_impl.InvalidArgumentError: Invalid name
- sql - MS Access SQL 比较连续行
- node.js - NodeJs Cluster.Fork 不是一个函数
- excel - 是/否按钮 VBA Excel。if-else 函数不起作用
- artifactory - artifactory 6.8.7 无法启动,因为无法连接到访问服务器
- angular - Angular Reactive Form - 使用属性绑定更改输入值
- python - 将行折叠为列 Pandas
- c# - C#如何在值为零时禁用按钮