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



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

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

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

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

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

最新更新