PySimpleGUI多窗口绑定及按钮仅文本区域可点击问题求助
PySimpleGUI 双窗口与按钮点击问题解决方案
问题1:双窗口同步最小化、取消置顶悬浮
解决步骤如下:
- 移除按钮窗口
top_window的keep_on_top=True参数,关闭强制置顶属性,避免切换其他程序时按钮窗口仍悬浮 - 绑定两个窗口的从属关系,将按钮窗口的tkinter父对象设置为背景窗口,实现父窗口最小化、激活状态同步联动
- 补全自定义标题栏最小化按钮的触发逻辑,点击时两个窗口同步执行最小化操作
问题2:按钮非文本区域点击无响应
该问题的核心原因是按钮背景色与按钮窗口设置的透明色完全一致,按钮的非文本黑色区域被系统判定为透明区域,点击时直接穿透到下层空白,不会触发按钮事件。
解决方法:
- 将所有按钮的背景色调整为和透明色有细微差别的颜色(例如
#010101,视觉上和纯黑无区别,不会被判定为透明) - 给按钮显式设置
size参数,主动扩大按钮的可点击范围
完整修改后代码
import os import sys import PySimpleGUI as sg sg.theme('DarkBlack') def resource_path(relative_path): bundle_dir = getattr( sys, '_MEIPASS', os.path.abspath(os.path.dirname(__file__))) return os.path.abspath(os.path.join(bundle_dir, relative_path)) def title_bar(title, text_color, background_color): bc = background_color tc = text_color font = 'ConsolasBlack 15' return [sg.Col([[sg.T(title, text_color=tc, background_color=bc, font=font, grab=True)]], pad=(0, 0), background_color=bc), sg.Col([[sg.T('─', text_color='white', background_color=bc, enable_events=True, font=font, key='-MINIMIZE-'), sg.Text('❎', text_color='white', background_color=bc, font=font, enable_events=True, key='Exit')]], element_justification='r', key='-C-', grab=True, pad=(0, 0), background_color=bc)] sg.Window._move_all_windows = True gifpath=resource_path("media/079.gif") image = sg.Image(gifpath, background_color='black',pad=(0, 0)) # 按钮修改背景色为#010101,添加size参数扩大点击区域 botones= [[sg.Button('CREDITS', button_color=('white', '#010101'), size=(10,2), pad=((0,0),(10,0)))], [sg.Button('MUTE', button_color=('white', '#010101'), size=(10,2), pad=((0,0),(70,0))),sg.Button('PAUSE', button_color=('white', '#010101'), size=(10,2), pad=((422,0),(70,0)))], [sg.Button('UNMUTE', button_color=('white', '#010101'), size=(10,2), pad=((0,0),(50,10))),sg.Button('UNPAUSE', button_color=('white', '#010101'), size=(10,2), pad=((382,0),(50,0)))]] background_layout=[title_bar('SCP-079 v0.4a ', sg.theme_text_color(), sg.theme_background_color()),[image]] buttonsLayout=botones window_background = sg.Window('', background_layout, finalize=True, no_titlebar=True, margins=(0, 0), element_padding=(0,0)) # 移除keep_on_top=True参数 top_window = sg.Window('SCP-079', buttonsLayout,size=(540,360), icon=resource_path("media/079.ico"), grab_anywhere=False, finalize=True, no_titlebar=True, transparent_color=sg.theme_background_color()) # 绑定双窗口从属关系 top_window.TKroot.transient(window_background.TKroot) while True: window, event, values = sg.read_all_windows(timeout=100) if event is None or event == 'Exit': break # 补全最小化按钮逻辑 if event == '-MINIMIZE-': window_background.minimize() top_window.minimize() # 原有业务逻辑保留 # if event =='Mute': # mute() # if event =='Unmute': # unmute() # if event =='Listen': # unpauselisten() # if event =='Listen': # pauselisten() # if event =='Credits': # popup_showinfo() # if event =='Hide': # sysTray() image.update_animation_no_buffering(image.Filename, 100) top_window.close() window_background.close()
内容的提问来源于stack exchange,提问作者user15437271
相关产品推荐
相关产品推荐

