在鼠标悬停时随机移动 tkinter 按钮

Move tkinter button randomly on mouse hover

我正在尝试让按钮随机移动到列表中的坐标。 每次我 运行 程序时,我第一次将鼠标悬停在它上面时它就会移动,此后再也没有,我无法弄清楚,我是一个完全的菜鸟,但坦率地说,我很惊讶它的工作原理。 我讨厌问问题,但几周来我一直在努力解决这个问题,所以我感谢任何人的帮助..

import tkinter as tk
from tkinter import *
import random

root = tk.Tk()
root.title('Press me')
root.geometry('1280x800')

img=PhotoImage(file='red_button_crop.png')
my_label=Label(root, text="",font='helvetica,12')
my_label.pack(pady=50)  

but_loc_x=[200,600,1000]
but_loc_y=[200,350,600]
but_pos_x=random.choice(but_loc_x)
but_pos_y=random.choice(but_loc_y)
def press():
    my_label.config(text="You pressed me.\n Well done\nYou are as clever as a monkey.\n Not one of the good ones tho")   
    root.after(1500,root.destroy)
    
def button_hover(e):
    root.after(250)
    button.place_configure(x=but_pos_x,y=but_pos_y)
    
#def unhover(e):
   # root.after(500)
    #button.place_configure(x=600,y=350)
    

    
button =tk.Button(root,image=img,borderwidth=0,command=press)
button.place(x=600,y=350,anchor=CENTER)

button.bind("<Enter>",button_hover)
#button.bind("<Leave>",unhover)





root.mainloop()

我已经尝试实现我在网上搜索到的各种代码,但我的知识还不足以解决它

重要的是,正如其中一条评论所暗示的那样,每次将鼠标悬停在按钮上时,按钮都会移动,因此您的代码实际上是正确的。

但是,因为坐标是在函数之外设置的,所以它总是悬停在同一个地方(所以它看起来好像没有移动)。

将代码更正为所需输出的更改如下。

  1. 删除了 from tkinter import * 并按原样使用了 tk 别名。
  2. random 按钮位置移动到函数中(请参阅带箭头的注释)。

这是代码的更正版本:

import tkinter as tk
# from tkinter import *
import random

root = tk.Tk()
root.title('Press me')
root.geometry('1280x800')

img=tk.PhotoImage(file='red_button_crop.png')
my_label=tk.Label(root, text="",font='helvetica,12')
my_label.pack(pady=50)  

but_loc_x=[200,600,1000]
but_loc_y=[200,350,600]
def press():
    my_label.config(text="You pressed me.\n Well done\nYou are as clever as a monkey.\n Not one of the good ones tho")   
    root.after(1500,root.destroy)
    
def button_hover(e):
    root.after(250)
    but_pos_x=random.choice(but_loc_x)   # <----- moved into the function
    but_pos_y=random.choice(but_loc_y)   # <----- moved into the function

    button.place_configure(x=but_pos_x,y=but_pos_y)
    
#def unhover(e):
   # root.after(500)
    #button.place_configure(x=600,y=350)
    

    
button =tk.Button(root,image=img,borderwidth=0,command=press)
button.place(x=600,y=350,anchor=tk.CENTER)

button.bind("<Enter>",button_hover)
#button.bind("<Leave>",unhover)

root.mainloop()

结果: 图像 red_button_crop.png 现在悬停时会随机移动。