我有一个更大的tkinter应用程序,我想以动态方式设置最上面的属性.我可以实现我想要的,但每次我判断TOPTOP的状态时,屏幕上选定的菜单栏就会消失.

要再现这一点,请考虑下面的MRE,在运行代码时,单击菜单栏上的"Menu"按钮,级联打开,退出按钮显示,看着它在check_topost函数运行后消失,但"Menu"按钮仍然以某种方式被按下.

注释掉判断属性的行或将其设置为True的行将停止行为

import tkinter as tk

def check_topmost():
    print(app.attributes('-topmost')) # comment this
    app.after(1000, check_topmost)

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
app.after(1000, check_topmost)
app.mainloop()

任何关于我做错了什么或者为什么会发生这样的事情的提示都非常感谢!

请原谅我的打字错误,这是我在手机上写的.

推荐答案

这不是对您的问题的修复,而是一种变通方法.看起来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()

Python相关问答推荐

计算所有前面行(当前行)中列的值

如何从具有多个嵌入选项卡的网页中Web抓取td类元素

替换字符串中的多个重叠子字符串

如何使用symy打印方程?

仿制药的类型铸造

抓取rotowire MLB球员新闻并使用Python形成表格

未删除映射表的行

为什么这个带有List输入的简单numba函数这么慢

django禁止直接分配到多对多集合的前端.使用user.set()

如何更改分组条形图中条形图的 colored颜色 ?

如何调整QscrollArea以正确显示内部正在变化的Qgridlayout?

Pre—Commit MyPy无法禁用非错误消息

UNIQUE约束失败:customuser. username

什么是合并两个embrame的最佳方法,其中一个有日期范围,另一个有日期没有任何共享列?

在Python中使用if else或使用regex将二进制数据如111转换为001""

如何在Python Pandas中填充外部连接后的列中填充DDL值

为什么t sns.barplot图例不显示所有值?'

使用polars. pivot()旋转一个框架(类似于R中的pivot_longer)

使用np.fft.fft2和cv2.dft重现相位谱.为什么结果并不相似呢?

在任何要保留的字段中添加引号的文件,就像在Pandas 中一样