如何在 Tkinter 中强制注意弹出窗口
Posted
技术标签:
【中文标题】如何在 Tkinter 中强制注意弹出窗口【英文标题】:How to make pop-up window with force attention in Tkinter 【发布时间】:2020-08-15 14:38:14 【问题描述】:我想创建一个在您输入之前不允许用户访问其他窗口的窗口。
我试过win.attribute("ontop", True)
,但它允许用户访问其他窗口。
或者在 Tkinter python 3.8 中有没有像 force_focus_lock()
这样的函数,它不允许其他窗口
在您输入或关闭当前窗口之前获得焦点。
【问题讨论】:
见How to create a modal dialog in tkinter?。 我更新了我的答案,提供了更多可能性和更彻底的实施。 【参考方案1】:我相信以下是您正在尝试做的事情。用 cmets 给出解释。
方法#1: (PopOut1)
您仍然可以移动主窗口 如果主窗口上有鼠标释放,新窗口将获得焦点方法 #2: (PopOut2)
主窗口被锁定 如果在主窗口上释放鼠标,新窗口将呈现焦点、闪烁和“叮”声import tkinter as tk
#first method
class PopOut1(tk.Toplevel):
def __init__(self, master, **kwargs):
tk.Toplevel.__init__(self, master, **kwargs)
self.geometry('400x300')
#set focus to this window
self.focus_set()
#releasing on any other tkinter window, within this process, forces focus back to this window
self.grab_set()
#second method
class PopOut2(tk.Toplevel):
def __init__(self, master, **kwargs):
tk.Toplevel.__init__(self, master, **kwargs)
self.geometry('400x300')
#set focus to this window
self.focus_set()
#disable the main window
master.attributes('-disabled', True)
#so this window can't end up behind the disabled window
#only necessary if this window is not transient
#self.attributes('-topmost', True)
#capture close event
self.protocol("WM_DELETE_WINDOW", self.close)
#event=None ~ in case you also want to bind this to something
def close(self, event=None):
#re-enable the main window
self.master.attributes('-disabled', False)
#destroy this window
self.destroy()
class App(tk.Tk):
TITLE = 'Application'
WIDTH, HEIGHT, X, Y = 800, 600, 50, 50
def __init__(self):
tk.Tk.__init__(self)
tk.Button(self, text="open popout 1", command=self.open1).grid()
tk.Button(self, text="open popout 2", command=self.open2).grid()
def open1(self):
PopOut1(self)
def open2(self):
#.transient(self) ~
# flash PopOut if focus is attempted on main
# automatically drawn above parent
# will not appear in taskbar
PopOut2(self).transient(self)
if __name__ == '__main__':
app = App()
app.title(App.TITLE)
app.geometry(f'App.WIDTHxApp.HEIGHT+App.X+App.Y')
#app.resizable(width=False, height=False)
app.mainloop()
【讨论】:
以上是关于如何在 Tkinter 中强制注意弹出窗口的主要内容,如果未能解决你的问题,请参考以下文章
tkMessageBox.showwarning 如何选择弹出的位置?