python - tkinter 在 MacOS 上始终使窗口保持在顶部

标签 python macos user-interface tkinter window

我正在尝试创建一个屏幕“窗帘”,它会阻挡除鼠标光标附近之外的屏幕部分。 在 Windows 上,使用 root.wm_attributes("-topmost", "true") 使窗口保持在顶部,即使我专注于另一个应用程序也是如此。但是,在 MacOS 上运行代码时,如果窗口焦点丢失,它将不会保持在最顶层。 MacOS 中相当于 -topmost 窗口管理器属性的是什么,无论焦点如何,该属性始终将窗口保持在顶部?

import tkinter as tk

class TransparentWindow(tk.Toplevel):
    """
    This class is just a Toplevel window.
    """
    def __init__(self, background="white", opacity=0.7):
        super(TransparentWindow, self).__init__()
        #self.master = master
        self.configure(background=background)
        self.overrideredirect(True)
        self.wm_attributes("-alpha", opacity)
        self.wm_attributes("-topmost", "true")
        self.lift()


if __name__ == '__main__':
    root = tk.Tk()
    TransparentWindow() 
    root.mainloop()

在 High Sierra 虚拟机中运行此代码会导致选择另一个窗口时,顶层不会始终位于顶部。

最佳答案

在 Mac OS 上使用 overrideredirect(True) 会禁用很多东西,例如 bindButton 按下和一些事件,老实说,我不知道不知道到底为什么。 (如果有人知道请评论)。至少在我的 Mac 上我遇到了这个问题,我已经阅读并发现并非所有 Mac 用户都有这个问题。

这就是为什么 root.wm_attributes("-topmost", "true") 不起作用。但别担心,我有一个解决方法。

<强> Here is your example which works exactly you want on my Mac.

从您的代码中我可以看出您想要一个无边框窗口,这是我在所有绑定(bind)和事件仍然有效的情况下执行此操作的方法。

I first put overrideredirect(True) then in the next line overrideredirect(False) Also you don't need root.lift() in this case.

好的,试试这段代码,看看按钮是否能正常按下。

示例

import tkinter as tk

root = tk.Tk()

root.overrideredirect(True)
# root.overrideredirect(False)  # Uncomment and try again.

tk.Button(root, text="Borderless").pack()
root.wm_attributes("-topmost", "true")
root.wm_attributes("-alpha", 0.7)
root.wm_attributes("-topmost", "true")

# Doesn't matter if you use lift() or not with the use of root.overrideredirect(False) as well
root.lift()                     

root.mainloop()

希望这对您有帮助。


这是您的代码,它完全符合您的要求(至少在我的 Mac 上)

import tkinter as tk

class TransparentWindow(tk.Toplevel):
    """
    This class is just a Toplevel window.
    """
    def __init__(self, background="white", opacity=0.7):
        super(TransparentWindow, self).__init__()
        #self.master = master
        self.configure(background=background)
        self.overrideredirect(True)
        self.overrideredirect(False)
        self.wm_attributes("-alpha", opacity)
        self.wm_attributes("-topmost", "true")
        # self.lift()

if __name__ == '__main__':
    root = tk.Tk()
    TransparentWindow() 
    root.mainloop()

关于python - tkinter 在 MacOS 上始终使窗口保持在顶部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55868430/

相关文章:

python - AWS boto - 实例状态/快照状态不会更新 Python While Loop

java - 卡经销商java gui

javascript - jQuery 工具(水平 Accordion )与 jQuery UI(选项卡)相结合?

python -regex匹配单词列表

Python:Elif 和 Else 不工作

Python 函数未运行,解释器未给出任何错误

ios - 将 iOS 应用程序移植到 Mac OS-X(音频捕获和播放)

cocoa - 忽略 "Attribute Unavailable"- Xcode4 中的警告

python - Lazarus 库在 OSX 的 Python 中使用 ctypes

python - wxPython:我应该如何在 Controller 中组织每个小部件数据?