在Macintosh(10.13.6)上使用Tkinter OptionMenu()小部件时出现奇怪的视觉行为

2024-05-03 15:39:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在使用一个GUI,让用户可以选择许多不同的颜色映射

问题是当OptionMenu()的下拉列表接近屏幕底部时,整个框向下移动到一个奇怪的位置。

我不确定这是一个bug还是我做错了什么。下面提供的示例代码,以及列表框下移前后发生的情况的图像(左和右分别有7个和8个以上的其他小部件)

请注意,如果您试图重现问题,您的解决方案可能需要较长的列表/较低的下拉列表

from tkinter import *

class GUI(Tk):
    def __init__(self):
        Tk.__init__(self)
        self.initGUI()

    def initGUI(self):
        self.cmapchoice = StringVar()
        self.cmapchoice.set('jet')
        self.cmaps = sorted(['viridis', 'plasma', 'inferno', 'magma','binary', 
            'bone','spring', 'summer', 'autumn', 'winter', 'cool','hot','copper','Spectral', 
            'coolwarm', 'bwr', 'seismic','twilight', 'hsv', 'Paired', 'Accent', 'prism', 'ocean', 
            'terrain','brg', 'rainbow', 'jet'],key=lambda s: s.lower())
        for i in range(8): # Change this to 7 to "fix" the issue
            Label(self,text='OTHER WIDGETS').grid(row=i, column=1, sticky='WE')
        OptionMenu(self,self.cmapchoice,*self.cmaps).grid(row=9, column=1, sticky='WE')

if __name__ == "__main__":
    MainWindow = GUI()
    MainWindow.mainloop()

enter image description here


Tags: toself列表initdefguicolumntk
2条回答

这个问题可以有一个解决办法,虽然这不是问题的确切解决办法,但可以解决问题。如果打开^{}上方的菜单(没有任何下拉菜单的OptionMenu小部件),则它将永远不会移动到屏幕底部

下拉菜单的方向可以用Menubutton^{}参数设置。就像这样

op = OptionMenu(...)
op['direction'] = 'above'

完整示例

from tkinter import *

class GUI(Tk):
    def __init__(self):
        Tk.__init__(self)
        self.initGUI()

    def initGUI(self):
        self.cmapchoice = StringVar()
        self.cmapchoice.set('jet')
        self.cmaps = sorted(['viridis', 'plasma', 'inferno', 'magma','binary', 
            'bone','spring', 'summer', 'autumn', 'winter', 'cool','hot','copper','Spectral', 
            'coolwarm', 'bwr', 'seismic','twilight', 'hsv', 'Paired', 'Accent', 'prism', 'ocean', 
            'terrain','brg', 'rainbow', 'jet'],key=lambda s: s.lower())
        for i in range(8): # Change this to 7 to "fix" the issue
            Label(self,text='OTHER WIDGETS').grid(row=i, column=1, sticky='WE')
        op = OptionMenu(self, self.cmapchoice, *self.cmaps)
        op.grid(row=9, column=1, sticky='WE')
        op['direction'] = 'above'

if __name__ == "__main__":
    MainWindow = GUI()
    MainWindow.mainloop()

虽然我仍然不知道该如何处理这个行为,但我了解到来自ttk的Combobox小部件无论如何要好得多,因为它更紧凑,并且在打开时不会占据整个屏幕

相关问题 更多 >