或使按钮背景透明

或使按钮背景透明

本文介绍了如何使按钮显示在背景后面,或使按钮背景透明?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(注意:带边框的按钮是背景的一部分)我想将真正的按钮放在图像后面,这样我就可以在背景中按下按钮,但是,我实际上是在按下它后面的按钮.

def __init__(self, parent, controller):tk.Frame.__init__(self, parent)self.controller = 控制器background_image = tk.PhotoImage(file="Mainmenu.png") # 显示文件中的内容background_label = tk.Label(self, image=background_image) # 使 tk.Label 显示 background_imagebackground_label.place(x=0, y=0, relwidth=1, relheight=1) # 调整高度/宽度background_label.image = background_image # 将标签识别为图片button1 = tk.Button(self, text="Play", bg="red", fg="black", height=2, width=15,命令=拉姆达:controller.show_frame(播放"))button2 = tk.Button(self, text="Settings", bg="yellow", fg="black", height=2, width=15,命令= lambda:controller.show_frame("设置"))button3 = tk.Button(self, text="Quit", bg="white", fg="black", height=2, width=15, cursor="pirate",命令=退出)button1.place(x="300",y="240")button2.place(x="480",y="240")button3.place(x="390",y="300")button1.config(font=("系统", 10))button2.config(font=("系统", 10))button3.config(font=("系统", 10))
解决方案
  1. 定义一个继承自tk.Canvas的类对象

    class Menu(tk.Canvas):def __init__(self, parent, image, command, show_areas=False):"""初始化一个 Canvas 对象,显示一个图像将鼠标单击绑定到函数初始化一个 dict 来保存添加的可点击区域:param parent: 父小部件:param image: 图像对象:param command: 处理区域点击的回调命令:param show_areas: 用于调试/跟踪目的.如果'True'显示可点击区域."""super().__init__(parent)# 向 TKinter 提供图像self._image = 图像self.create_image(0, 0, image=self._image, anchor='nw')self.callback = 命令self.bind('', self.Button_1_func)self.show_areas = show_areasself.areas = {}

  2. 鼠标点击处理函数.
    搜索匹配区域并使用 tag

    调用 .callback 函数

     def Button_1_func(self, event):对于 self.areas.items() 中的标签 (x, y, x2, y2):如果 event.x 在 range(x, x2) 中并且 event.y 在 range(y, y2) 中:event.tag = 标签self.callback(事件)返回休息"

  3. 使用给定的 tag 和计算出的几何图形添加一个新的可点击区域.
    15 * 10 计算面积 width
    5 * 10 计算面积 height
    如果 self.show_areasTrue,则使用几何图形创建一个矩形.

     def add_area(self, tag, coord):self.areas[tag] = *coord, (coord[0] + (15 * 10)) + 1, (coord[1] + (5 * 10)) + 1如果 self.show_areas:self.create_rectangle(self.areas[tag])

用法:

类应用程序(tk.Tk):def __init__(self):super().__init__()# 将文件中的内容显示为 background_imageself.menu = 菜单(自我,image=tk.PhotoImage(file="Mainmenu.png"),命令=self.command,show_areas=真)self.menu.place(x=0, y=0, relwidth=1, relheight=1)用于标记,坐标 [('Play', (300, 240)),('设置', (480, 240)),('退出', (390, 300))]:self.menu.add_area(标签,坐标)def show_frame(self, key):# 模拟controller.show_frame打印('show_frame({})'.format(key))def 命令(自我,事件):如果 ['Play', 'Settings'] 中的 event.tag:self.show_frame(event.tag)如果 event.tag == '退出':self.quit()如果 __name__ == "__main__":应用程序().主循环()

使用 Python 测试:3.5

(Note: The buttons with borders are part of the background)I would like to place the real buttons behind the image so it would like i'm pressing the button in the background, however, i'm actually pressing the button behind it.

def __init__(self, parent, controller):
    tk.Frame.__init__(self, parent)
    self.controller = controller

    background_image = tk.PhotoImage(file="Mainmenu.png")  # Displays whats in the file
    background_label = tk.Label(self, image=background_image)  # Makes tk.Label display the background_image
    background_label.place(x=0, y=0, relwidth=1, relheight=1)  # Adjusts the height/width

    background_label.image = background_image  # Recognises the label as an image

    button1 = tk.Button(self, text="Play", bg="red", fg="black", height=2, width=15,
                        command=lambda: controller.show_frame("Play"))
    button2 = tk.Button(self, text="Settings", bg="yellow", fg="black", height=2, width=15,
                        command=lambda: controller.show_frame("Settings"))
    button3 = tk.Button(self, text="Quit", bg="white", fg="black", height=2, width=15, cursor="pirate",
                        command=exit)

    button1.place(x="300",y="240")
    button2.place(x="480",y="240")
    button3.place(x="390",y="300")
    button1.config(font=("System", 10))
    button2.config(font=("System", 10))
    button3.config(font=("System", 10))
解决方案
  1. Define a class object inherited from tk.Canvas

    class Menu(tk.Canvas):
        def __init__(self, parent, image, command, show_areas=False):
            """
            Init a Canvas object, displaying a image
            Bind the Mouse click to a function
            Init a dict to hold the added clickable areas
    
            :param parent: The parent widget
            :param image: The image object
            :param command: The callback command to handle area clicks
            :param show_areas: For debug/trace purpose. If 'True'show the clickable areas.
            """
            super().__init__(parent)
            # Feed TKinter the image
            self._image = image
            self.create_image(0, 0, image=self._image, anchor='nw')
    
            self.callback = command
            self.bind('<Button-1>', self.Button_1_func)
    
            self.show_areas = show_areas
            self.areas = {}
    

  2. The Mouse-Click-Handler function.
    Search for a matching area and call the .callback function with the tag

        def Button_1_func(self, event):
            for tag, (x, y, x2, y2) in self.areas.items():
                if event.x in range(x, x2) and event.y in range(y, y2):
                    event.tag = tag
                    self.callback(event)
                    return 'break'
    

  3. Add a new clickable area with given tag and computed geometry.
    15 * 10 computes the area width
    5 * 10 computes the area height
    If self.show_areas is True, create a rectangle with the geometry.

        def add_area(self, tag, coord):
            self.areas[tag] = *coord, (coord[0] + (15 * 10)) + 1, (coord[1] + (5 * 10)) + 1
    
            if self.show_areas:
                self.create_rectangle(self.areas[tag])
    

class App(tk.Tk):
    def __init__(self):
        super().__init__()

        # Displays as background_image what's in the file
        self.menu = Menu(self,
                         image=tk.PhotoImage(file="Mainmenu.png"),
                         command=self.command,
                         show_areas=True)
        self.menu.place(x=0, y=0, relwidth=1, relheight=1)

        for tag, coords in [('Play', (300, 240)),
                            ('Settings', (480, 240)),
                            ('Quit', (390, 300))]:
            self.menu.add_area(tag, coords)

    def show_frame(self, key):
        # Simulating controller.show_frame
        print('show_frame({})'.format(key))

    def command(self, event):
        if event.tag in ['Play', 'Settings']:
            self.show_frame(event.tag)

        if event.tag == 'Quit':
            self.quit()

if __name__ == "__main__":
    App().mainloop()

Tested with Python: 3.5

这篇关于如何使按钮显示在背景后面,或使按钮背景透明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 23:57