I want to create a window which doesn’t allow the user to access other windows until you give an input.
I tried win.attribute("ontop", True)
but it allows the user to access other windows.
or is there any function like a force_focus_lock()
in Tkinter python 3.8 which doesn’t allow other window to
get focus until you give a input or the close present window.
Advertisement
Answer
I believe the below is what you are trying to do. Explanation is given in comments.
method #1: (PopOut1)
- you can still move the main window
- the new window assumes focus if there is a mouse release on main window
method #2: (PopOut2)
- the main window is locked in place
- the new window will assume focus, blink and “ding” if there is a mouse release on main window
JavaScript
x
70
70
1
import tkinter as tk
2
3
4
#first method
5
class PopOut1(tk.Toplevel):
6
def __init__(self, master, **kwargs):
7
tk.Toplevel.__init__(self, master, **kwargs)
8
self.geometry('400x300')
9
10
#set focus to this window
11
self.focus_set()
12
13
#releasing on any other tkinter window, within this process, forces focus back to this window
14
self.grab_set()
15
16
17
#second method
18
class PopOut2(tk.Toplevel):
19
def __init__(self, master, **kwargs):
20
tk.Toplevel.__init__(self, master, **kwargs)
21
self.geometry('400x300')
22
23
#set focus to this window
24
self.focus_set()
25
26
#disable the main window
27
master.attributes('-disabled', True)
28
29
#so this window can't end up behind the disabled window
30
#only necessary if this window is not transient
31
#self.attributes('-topmost', True)
32
33
#capture close event
34
self.protocol("WM_DELETE_WINDOW", self.close)
35
36
#event=None ~ in case you also want to bind this to something
37
def close(self, event=None):
38
#re-enable the main window
39
self.master.attributes('-disabled', False)
40
#destroy this window
41
self.destroy()
42
43
44
class App(tk.Tk):
45
TITLE = 'Application'
46
WIDTH, HEIGHT, X, Y = 800, 600, 50, 50
47
48
def __init__(self):
49
tk.Tk.__init__(self)
50
tk.Button(self, text="open popout 1", command=self.open1).grid()
51
tk.Button(self, text="open popout 2", command=self.open2).grid()
52
53
def open1(self):
54
PopOut1(self)
55
56
def open2(self):
57
#.transient(self) ~
58
# flash PopOut if focus is attempted on main
59
# automatically drawn above parent
60
# will not appear in taskbar
61
PopOut2(self).transient(self)
62
63
64
if __name__ == '__main__':
65
app = App()
66
app.title(App.TITLE)
67
app.geometry(f'{App.WIDTH}x{App.HEIGHT}+{App.X}+{App.Y}')
68
#app.resizable(width=False, height=False)
69
app.mainloop()
70