首页 > 解决方案 > 放置到另一个按钮时如何获取按钮的新位置?

问题描述

有没有办法为循环产生的按钮分配一个整数值?我想要在这里发生的事情是在点击时将按下的按钮放置到某个位置,当再次点击该按钮时,它将返回到原来的位置。

我尝试使用 rooty 或 rootx 方法,使用一个保存按钮原始坐标的字典,称为 origvals。然后将其与单击时按钮的新位置进行比较,但它不起作用,而是给了我相同的结果。有人可以告诉我最好的方法吗?我想给每个按钮一个 0 值并在按下它时添加该值 1 以形成模数条件,以便它在按下时返回并在再次按下时返回到某个位置。

from tkinter import *
import string
import random

root = Tk()
root.geometry('400x400')


# New Buttons coordinates when clicked
buttons = {}
# X coordinate after being clicked
ax=20
# Original Buttons coordinates; this must be their position once clicked again
origvals = {}


def Enter(Value):
    global ax
    print(buttons)
    print(origvals)
    print(buttons[Value].winfo_rooty())    

    if buttons[Value].winfo_rooty() != origvals[Value]:
        buttons[Value].place(x=ax,y=150)
        ax+=20
    else:
        buttons[Value].place(x=origvals[Value][0],y=origvals[Value][1])

    print(buttons[Value].winfo_rooty())

    print(origvals[Value])




letters = string.ascii_uppercase

# Original x and y position
a=100
b=300
c=100
# Placement of random letter buttons
for i in range(1,13):
    x = random.randint(0,25)
    if i > 6:
        buttons[letters[x]] = Button(root, text = letters[x],command=lambda val=letters[x]:Enter(val))
        buttons[letters[x]].place(x=c,y=330)
        origvals[letters[x]] = [c,330]
        c+=20

    else:
        buttons[letters[x]] = Button(root, text = letters[x],command=lambda val=letters[x]:Enter(val))
        buttons[letters[x]].place(x=a,y=b)
        origvals[letters[x]] = [a,b]


    a+=20

mainloop()

所以你看,它有点像文字游戏,你按每个字母组成一个单词,当一个字母被点击两次时,它会回到原来的位置。

标签: pythontkinter

解决方案


推荐阅读