How to disable the movement of the Tkinter Window without removing the title bar

Viewed 280

I have been creating an application for taking the test. So, for that, I have to do two things. First, disable the drag of the Tkinter window and don't let the user focus on other windows rather than my application window. This means I wanted to make my application such that, No other application can be used while my application is in use.

2 Answers

Try this:

import tkinter as tk


class FocusedWindow(tk.Tk):
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

        # Force it to be unminimisable
        super().overrideredirect(True)

        # Force it to always be on the top
        super().attributes("-topmost", True)

        # Even if the user unfoceses it, focus it
        super().bind("<FocusOut>", lambda event: self.focus_force())

        # Take over the whole screen
        width = super().winfo_screenwidth()
        height = super().winfo_screenheight()
        super().geometry("%ix%i+0+0" % (width, height))


root = FocusedWindow()
# You can use it as if it is a normal `tk.Tk()`
button = tk.Button(root, text="Exit", command=root.destroy)
button.pack()
root.mainloop()

That removed the title bar but you can always create your own one by using tkinter.Labels and tkinter.Buttons. I tried making it work with the title bar but I can't refocus the window for some reason.

One way to do this is by the following, another could be to overwrite the .geometry() method of tkinter.

In the following code I simply had get the position by using winfo_rootx and winfo_rooty. After this you can force the window by calling the geometry method via binding the event every time the window is configured.

import tkinter as tk

def get_pos():
    global x,y
    x = root.winfo_rootx()
    y = root.winfo_rooty()
def fix_pos():
    root.bind('<Configure>', stay_at)
def stay_at(event):
    root.geometry('+%s+%s' % (x,y))

root = tk.Tk()
button1 = tk.Button(root, text='get_pos', command=get_pos)
button2 = tk.Button(root, text='fix_pos', command=fix_pos)

button1.pack()
button2.pack()

root.mainloop()
Related