Как добавить прозрачные кнопки на уже существующий фон в Python? - PullRequest
0 голосов
/ 11 апреля 2019

Я нигде не могу найти ответ на свой вопрос, поэтому я решил спросить здесь.

Я запускаю проект Python и хочу добавить несколько кнопок на фоне моего приложения.Я пробую Tkinter, но это добавляет «окно» в окне моего приложения, а не кнопку.

Я хочу прозрачные кнопки, потому что на моем фоне уже есть графические кнопки.Каждая кнопка будет выполнять команду.

1 Ответ

0 голосов
/ 11 апреля 2019

Поскольку вы говорите, что фон уже имеет вид кнопки, вам не нужно добавлять дополнительную кнопку.Вместо этого вы должны определить координаты ограничивающего прямоугольника для каждой «псевдокнопки», а затем создать привязки событий, которые будут выполнять действия, если пользователь нажимает в этих пределах.

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

...