如何在Python中已经存在的背景上添加透明按钮?

时间:2019-04-10 22:06:21

标签: python button tkinter transparent

我在任何地方都找不到答案,所以我决定在这里问。

我为一个Python项目加星标,我想在应用程序的背景上添加一些按钮。 我尝试使用Tkinter,但这会在我的应用程序窗口中添加一个“子窗口”,而不是按钮。

我想要透明的按钮,因为在我的背景中已经有图形按钮。每个按钮都会执行一个命令。

1 个答案:

答案 0 :(得分:0)

由于您说背景已经具有按钮外观,因此您无需添加其他按钮。相反,您应该为每个“伪按钮”确定边界矩形的坐标,然后创建事件绑定,如果用户在这些边界内单击,将执行操作。

class Rectangle:
    def __init__(self, x1, y1, x2, y2):
        # (x1, y1) is the upper left point of the rectangle
        # (x2, y2) is the lower right point of the rectangle
        self.x1 = x1
        self.y1 = y1
        self.x2 = x2
        self.y2 = y2
        return

    def contains(self, newx, newy):
        # Will return true if the point (newx, newy) lies within the rectangle.
        # False otherwise.
        return (self.x1 <= newx <= self.x2) and (self.y1 <= newy <= self.y2) 


try:
    import tkinter as tk
except:
    import Tkinter as tk
from PIL import ImageTK, Image


def button_click(event):
    # The location of the click is stored in event sent by tkinter
    # and can be accessed like:
    print("You clicked ({}, {})".format(event.x, event.y))

    ## Now that you're in here, you can determine if the user clicked
    ## inside one of your buttons. If they did, perform the action that
    ## you want. For example, I've created two rectangle objects which
    ## simulate the location of some.

    button1_rect = Rectangle( 100, 100, 200, 200 )
    button2_rect = Rectangle( 300, 300, 400, 400 )
    # Change the rectangles to reflect your own button locations.

    if button1_rect.contains(event.x, event.y):
        print("You clicked button number 1!")

    if button2_rect.contains(event.x, event.y):
        print("You clicked button number 2!")


    return

root = tk.Tk()
canvas = tk.Canvas(master = root, height = 500, width = 500)

canvas.bind("<Button-1>", button_click)
# The above command means whenever <Button-1> (left mouse button) is clicked
# within your canvas, the button_click function will be called. 

canvas.pack()
your_background = ImageTK.PhotoImage(Image.open("info_screen.png")) # <-- Or whatever image you want...
canvas.create_image(20, 20, image = your_background)
# 20, 20 represents the top left corner for where your image will be placed

root.mainloop()

运行它,然后在观看控制台的同时单击鼠标

在此处了解有关绑定到tkinter事件的更多信息:https://effbot.org/tkinterbook/tkinter-events-and-bindings.html