拖动画布时获取当前值

时间:2019-04-11 11:58:48

标签: python python-3.x tkinter drag

我正在尝试制作一个简单的纸牌游戏,例如纸牌。 我没有编码方面的经验,请原谅我,这是一个简单的问题。

我想移动一些画布对象。新对象具有正确的值,但是当我拖动已经存在的卡时,它将显示错误的值(荷兰语中的waarde)。我想将值(waarde)绑定到卡上,但是不知道该怎么做...

关于标签,绑定,ID ......

from tkinter import *
from random import randint

window = Tk()

deck = [1,2,3,4,5,6]

def pakkaart():
    rand_card = randint(0,len(deck)-1)
    global waarde
    waarde = deck[rand_card]
    deck.pop(rand_card)
    global kaart
    kaart = Canvas(window, width = 40, height = 40, bg='yellow')
    kaart.place(x=50, y=50, anchor=CENTER)
    kaart.create_text(20,20,text=(waarde))
    kaart.bind("<B1-Motion>", drag)


def drag(event):
    event.widget.place(x=event.x_root, y=event.y_root,anchor=CENTER)    
    print(waarde)

button1 = Button(window, text="Nieuwe Kaart", command=pakkaart)
button1.pack()

window.mainloop()

因此本质上是在寻找一种将值绑定到画布的方法。

1 个答案:

答案 0 :(得分:0)

您上面的代码可以正常工作,它显示正确的值,但是如果您愿意,可以尝试一下

from tkinter import *
from random import randint

window = Tk()
ws = window.winfo_screenwidth()
hs = window.winfo_screenheight()
w = 500  # width for the Tk root
h = 300  # height for the Tk root
x = (ws / 2) - (w / 2)
y = (hs / 2) - (h / 2)

window.geometry('%dx%d+%d+%d' % (w, h, x, y))

deck = [1, 2, 3, 4, 5, 6]


def pick_card():
    global waarde, kaart
    rand_card = randint(0, len(deck)-1)
    card_number = deck[rand_card]
    deck.remove(card_number)
    card = Canvas(window, width=40, height=40, bg='yellow')
    card.place(x=50, y=50, anchor=CENTER)
    card_number_text = card.create_text(20, 20, text=card_number, tags=card_number)
    card.bind("<Button-1>", lambda event: get_number(event, card_number_text))  # or you can use: card.bind("<Button-1>", lambda event: print(card_number))
    card.bind("<B1-Motion>", drag)


def drag(event):
    # This is better for move a widget
    cx = window.winfo_pointerx() - window.winfo_rootx()
    cy = window.winfo_pointery() - window.winfo_rooty()
    event.widget.place(x=cx, y=cy)

def get_number(event, number):
    print(event.widget.itemcget(number, "text"))


button1 = Button(window, text="Generate Card", command=pick_card)
button1.pack()


window.mainloop()

我已经修改了drag(event)函数,并写了两种获取当前卡值的方法,要存储它,您可以使用一些global varibles或创建一个class,第二种方法是更好