Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tkinter Toplevel always in front

Tags:

python

tkinter

I am working on a program that uses a tkinter TopLevel window to display periodically updating log information to the user. My problem is that the main program is fullscreen, so whenever they interact with it after opening the log window, the log window isn't visible since it is now behind the main program.

Is there a way to force a Toplevel window (or actually, any Tkinter window) to remain permanently ontop of all other windows?

Consider this quick setup for example:

import tkinter as tk
from tkinter import ttk

class Example(tk.Frame):

    def __init__(self, master, *args, **kwargs):
        tk.Frame.__init__(self, master, *args, **kwargs)
        self.pack()
        btn = ttk.Button(self, text = "Press", command = self.openTopLevel)
        btn.pack()

    def openTopLevel(self):
        topLevelWindow = tk.Toplevel(self)

root = tk.Tk()
main = Example(root)
root.mainloop()

When you Press the button and open the Toplevel Window, it is on top. But if you grab the Frame, move it around, etc, the Toplevel goes behind it. How do I stop that? Or is that not something Tkinter allows me to do?

like image 532
Skitzafreak Avatar asked Dec 03 '22 21:12

Skitzafreak


1 Answers

To make a window stay in front of others in a tkinter application, use
attributes('-topmost', 'true'). In your code, it is a one-line to add.

import tkinter as tk
from tkinter import ttk

class Example(tk.Frame):

    def __init__(self, master, *args, **kwargs):
        tk.Frame.__init__(self, master, *args, **kwargs)
        self.pack()
        btn = ttk.Button(self, text = "Press", command = self.openTopLevel)
        btn.pack()

    def openTopLevel(self):
        topLevelWindow = tk.Toplevel(self)
        # Make topLevelWindow remain on top until destroyed, or attribute changes.
        topLevelWindow.attributes('-topmost', 'true')

root = tk.Tk()
main = Example(root)
root.mainloop()
like image 77
Ron Norris Avatar answered Mar 23 '23 05:03

Ron Norris