我正在嘗試使按鈕隨機移動到串列中的坐標。我每次運行程式時第一次將滑鼠懸停在它上面時它就會移動,之后就再也沒有了,我無法弄清楚,我是一個完全的菜鳥,但坦率地說,我很驚訝它的作業原理。我討厭問問題,但我已經嘗試解決這個問題好幾個星期了,所以我感謝任何人的幫助..
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()
我試過實作我在網上搜索到的各種代碼,但我知道的還不夠多
uj5u.com熱心網友回復:
重要的是,正如其中一條評論所暗示的那樣,每次將滑鼠懸停在按鈕上時按鈕都會移動,因此您的代碼實際上是正確的。
但是,因為坐標是在函式之外設定的,所以它總是懸停在同一個地方(所以它看起來好像沒有移動)。
將代碼更正為所需輸出的更改如下。
- 洗掉并按原樣
from tkinter import *使用別名。tk - 將
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現在在懸停時隨機移動。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/448497.html
