user3448301
user3448301

Reputation: 13

tkinter Option Menu Is missing

Why does the following code from my in initUI, a method called by __ init __, not add an Option menu to the window? I thought this code would make a window with a OptionMenu in it.

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")

full code:

'''
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")

Upvotes: 1

Views: 297

Answers (1)

atlasologist
atlasologist

Reputation: 3964

You need to use the pack() method on your Frame in init, otherwise the argument self within your OptionMenu doesn't refer to an existing Frame.

Try this:

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")

Alternatively, the parent widget is self.parent, so you could make that the master of self.game_menu:

 self.game_menu = tk.OptionMenu(self.parent, game_menu_var, 1, 2 , 3)

Upvotes: 1

Related Questions