在另一个全屏窗口 tkinter python 上显示顶层窗口

时间:2021-03-11 14:52:30

标签: python tkinter

我对 tkinter 窗口的全屏属性有疑问。主窗口具有全屏属性,第二个窗口必须显示在主窗口的顶部,在单击外部时不会丢失。有什么帮助吗?

# add the necessairy librairy
import tkinter as tk

def Region_windows2():
    #master is the second window with toplevel option
    master = tk.Toplevel(Mafenetre) #removed your mainframe class

    w = 300 # width for the Tk root
    h = 200 # height for the Tk root
    # get screen width and height
    ws = master.winfo_screenwidth() # width of the screen
    hs = master.winfo_screenheight() # height of the screen
    # calculate x and y coordinates for the Tk master window
    x = (ws/2) - (w/2)
    y = (hs/2) - (h/2)
    # set the dimensions of the screen 
    # and where it is placed
    master.geometry('%dx%d+%d+%d' % (w, h, x, y))
    # when open the second window i want it to be on toplevel; it means when i click outside the frame it won't get hide
    master.attributes("-topmost", True)
    master.title("password")

# here's the main window
Mafenetre = tk.Tk()
#set main window title
Mafenetre.title("GUI")
Mafenetre['bg']='white' # couleur de fond
# get screen width and height
wf1= Mafenetre.winfo_screenwidth()
hf1= Mafenetre.winfo_screenheight()
A = str(wf1)
B = str(hf1)
# set the dimensions of the screen 
# and where it is placed
Mafenetre.geometry(A+"x"+B)
Mafenetre.attributes('-fullscreen', True)
# add menubar to the main window
menubar = tk.Menu(Mafenetre, bg='#1f1b13', fg='white')
# menubar button to test the second window
menubar.add_command(label="tester", command=Region_windows2)
# add menubr to the main window
Mafenetre.config(menu=menubar)
Mafenetre.mainloop()

1 个答案:

答案 0 :(得分:3)

这个问题取决于窗口管理器如何处理全屏窗口,因此,在某些情况下,只需使用 master.attributes("-topmost", True) 就足以将顶层保持在主窗口的顶部。但是,在我的情况下(Linux、XFCE 桌面环境),它不起作用。我发现的解决方法是在顶层失去焦点时重新聚焦与 <FocusOut> 的绑定:

master.bind('<FocusOut>', lambda ev: master.focus_force())

Region_windows2()

请注意,此解决方法显然会阻止在打开顶层时在主窗口的 TextEntry 小部件中写入任何内容,但如果主窗口被“禁用”,则这不是问题(例如在顶层使用 .grab_set())。

相关问题