这不是对您的问题的修复,而是一种变通方法.看起来topmost
属性真的很奇怪……首先,它是特定于平台的.其次,一旦设置好了,它就不仅仅是改变了.如果将另一个窗口设置为"-topmost", 1
,则这两个窗口将具有相同的属性.在我找到的documentation个中,有"-topmost gets or sets whether this is a topmost window"
个.我假设,一旦您调用该属性,它不仅会判断该属性,还会重新赋值,从而为您提供带有下拉菜单的奇怪行为.有趣的是,如果你在app.attributes()
年前同时获得所有属性,你的下拉菜单不会受到影响.因此,您可以使用此解决方法来判断属性,并仅在必要时设置它.很可能,这不是最好的解决方案,但这是我能想到的最好的解决方案.
import tkinter as tk
def set_topmost():
app2.attributes('-topmost', 1)
print('window 1', app.attributes())
print('window 2', app2.attributes()) # as you can see both windows can have the same topmost attribute
app.attributes('-topmost', 0) # try the behavior after commenting this out
def check_topmost():
print(app.attributes()) # this does not affect your window/drop-down menu
att = str(app.attributes()) # making it a string as workaround
if "'-topmost', 1" in att:
print('already set as topmost')
else:
print('switch topmost')
app.attributes('-topmost', 1) # this will still disrupt your drop down menu
app.after(5000, check_topmost) # i set it to 5 seconds to better see the effects
app = tk.Tk()
menu_bar = tk.Menu(app)
sub_menu = tk.Menu(menu_bar, tearoff=0)
sub_menu.add_command(label = 'exit', command = app.destroy)
menu_bar.add_cascade(label = "menu", menu = sub_menu)
app.config(menu = menu_bar)
app.attributes('-topmost', 1) # comment this
app2 = tk.Toplevel()
app2.geometry('500x500')
btn = tk.Button(app, text='set topmost', command=set_topmost)
btn.pack()
app.after(1000, check_topmost)
app.mainloop()