tkinter选项菜单缺失

时间:2014-03-21 22:19:42

标签: python-3.x tkinter tk optionmenu

为什么我的initUI中的以下代码(__ init __调用的方法)不向窗口添加选项菜单?我认为这段代码会在其中创建一个OptionMenu的窗口。

game_menu_var = tk.IntVar()
game_menu_var.set(1)
self.game_menu = tk.OptionMenu(self, game_menu_var, 1, 2 , 3)
self.game_menu.pack(side="left")

完整代码:

'''
A GUI for wm
'''

import tkinter as tk
import _wm

class WMGUI(tk.Frame):
    '''
    A GUI for wm
    '''
    def __init__(self, parent=None, *, title='WM'):
        if parent is None:
            parent = tk.Tk()
        tk.Frame.__init__(self, parent)
        self.parent = parent
        self.initUI(title)

    def initUI(self, title):
        """
        do not call from outside of class
        """
        self.parent.title(title)
        # make game_menu
        game_menu_var = tk.IntVar()
        game_menu_var.set(1)
        self.game_menu = tk.OptionMenu(self, game_menu_var, 1, 2 , 3)
        self.game_menu.pack(side="left")

1 个答案:

答案 0 :(得分:1)

您需要在 init 中的pack()上使用Frame方法,否则self中的参数OptionMenu不会使用Frame。 t引用现有的class WMGUI(tk.Frame): ''' A GUI for wm ''' def __init__(self, parent=None, *, title='WM'): if parent is None: parent = tk.Tk() tk.Frame.__init__(self, parent) self.parent = parent self.pack() #packs the Frame self.initUI(title) def initUI(self, title): """ do not call from outside of class """ self.parent.title(title) # make game_menu game_menu_var = tk.IntVar() game_menu_var.set(1) self.game_menu = tk.OptionMenu(self, game_menu_var, 1, 2 , 3) self.game_menu.pack(side="left")

试试这个:

self.parent

或者,父窗口小部件是 self.game_menu = tk.OptionMenu(self.parent, game_menu_var, 1, 2 , 3) ,因此您可以将其作为self.game_menu的主人:

{{1}}