Tkinter:如何在画布上移动小部件?

时间:2015-06-29 16:51:25

标签: python canvas tkinter widget move

我试着做一个简单的应用程序,在画布上移动每个小部件。第一步我移动了一个矩形,但现在我想移动一个小部件!我想"这将是同样的事情!"但我错了:( 这是我的代码:

from tkinter import *

clicked = False

def callback(event):
    global clicked, start, pre_x,pre_y

    if clicked:
        clicked = False

    else:
        if event.x >= canvas.coords(rec)[0] and event.x <= canvas.coords(rec)[2] and event.y >= canvas.coords(rec)[1] and event.y <=canvas.coords(rec)[3]:
            clicked = True
            canvas.itemconfig(rec,fill = "blue")
            pre_x = event.x
            pre_y = event.y
            canvas.bind("<B1-Motion>",movement)

def movement(event):
    global clicked, start, pre_x,pre_y

    if clicked:
        x_diff = event.x - pre_x
        y_diff = event.y - pre_y
        #print("RecCoord[1]=" + str(canvas.coords(rec)[1]))
        pre_x = event.x
        pre_y = event.y
        #print("RecCoord[1] = " + str(canvas.coords(rec)[1]))
        canvas.move(rec,x_diff,y_diff)

window = Tk()
w = window.winfo_screenwidth()
h = window.winfo_screenheight()
window.geometry('%dx%d+0+0' % (w, h))
window.title('Finestra di disegno')
canvas = Canvas(window, width = w, height = h)
rec = canvas.create_rectangle(100,100, 100 + 55,100 + 26)
canvas.pack()
tmpbutton = Button(window, text = "Click me!")
tmpbutton.pack()
tmpbutton.update()

canvas.create_window(100,100, window = tmpbutton, anchor = NW, tags = 'button')
canvas.bind("<Button-1>",callback)
tmpbutton.bind("<Button-1>",callback)
window.mainloop()

我的想法是在按钮小部件下创建一个矩形,所以当我移动矩形时,我可以刷新按钮与矩形的新坐标!但是画布不会在小部件上捕获事件,因为每个小部件都有一个事件处理程序,对吗?所以我也绑定按钮小部件,但没有结果! 有人能帮我吗??我重复我的问题,我需要在画布上移动一个小部件,就像我对矩形一样...非常感谢:D

0 个答案:

没有答案