在tkinter中使用类似GoogleMaps的按钮

时间:2013-12-13 09:44:07

标签: python user-interface tkinter zoom

我想使用这样的按钮

enter image description here

而不是tkinter绘制的经典按钮:

Tk.Button(root, text = "Moveup", command=moveup).place(x=10,y=10)
Tk.Button(root, text = "Movedown", command=movedown).place(x=10,y=40)
Tk.Button(root, text = "Moveleft", command=moveleft).place(x=10,y=70)
Tk.Button(root, text = "Moveright", command=moveright).place(x=10,y=100)

更干净的方法是什么?(我看到过小部件重叠的脏解决方案,但我不确定这是最好的解决方案)。

1 个答案:

答案 0 :(得分:2)

在这种情况下你不需要任何按钮,更容易使用events and bindings

提供了图片:

enter image description here

要检测是否在上图中点击了up,down,right or left箭头,您可以检查它是否在图像特定部分的范围内:


最后代码:

import Tkinter as Tk
from PIL import Image, ImageTk

root = Tk.Tk()
root.geometry("600x360+100+50")
canvas = Tk.Canvas(root)
canvas.grid(sticky=Tk.N+Tk.E+Tk.S+Tk.W)

width = 300
height = 180

image_file = Image.open("above_image.png")
PIL_image = ImageTk.PhotoImage(image_file.convert("RGBA"))
canvas_img = canvas.create_image(width,height,image=PIL_image)

def callback(event):
    """ This function is called whenever a event occurs """
    if width-9 < event.x < width+9 and height-24 < event.y < height-12:
        print "clicked up arrow!"
    elif width-9 < event.x < width+9 and height+12 < event.y < height+24:
        print "clicked down arrow!"
    elif width+12 < event.x < width+25 and height-8 < event.y < height+8:
        print "clicked right arrow!"
    elif width-25 < event.x < width-12 and height-8 < event.y < height+8:
        print "clicked left arrow!"

canvas.bind("<Button-1>", callback)
root.mainloop()