#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2013
    Posts
    4
    Rep Power
    0

    Button to Window


    Hey,

    I am very new to python programming (emphasis on very), and am trying to write a program in which when I click on a button, a new window appears. I have seen answers to similar questions, but they are a little over my head and do not explain whats going on.

    The goal I am going for is a basic recipe book, and the buttons will say "breakfast" "lunch" "dinner" so when you click on one button, say "lunch," a new window will open with more buttons on it with labels such as "turkey sandwich."

    Can someone help me with this coding? I know how to make the frame and buttons, but this next step is stumping me.

    edit: I have discovered the Tkinter Toplevel Widget and am learning its properties.
  2. #2
  3. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,894
    Rep Power
    481
    Have the command activated by an event open a new top level with all your good new menu.

    Sounds painful.

    Can you make standard old drop down menus fit your project?
    [code]Code tags[/code] are essential for python code and Makefiles!
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2013
    Posts
    4
    Rep Power
    0
    Yeah I could. That might be better actually! How would I go about doing that?

    edit: When you click a selection from the drop-down menu list, the box displays text- so when you click "waffles" the box will show text on how to make waffles.
  6. #4
  7. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,894
    Rep Power
    481
    Waffles are better if you toast walnut pieces in the waffle maker for a short time before you add the batter.
    [code]Code tags[/code] are essential for python code and Makefiles!
  8. #5
  9. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,894
    Rep Power
    481
    To do: 1) put the master kill switch somewhere smart on the root window. 2) document the code. 3) under button packing include fill=tkinter.BOTH . 4) maybe the quit buttons should destroy all children as well as the immediate button.

    This program implements your original idea. To modify it to display your own data you will need to understand the dictionary connected to the variable `menu'.

    The data input to main is a dictionary of dictionaries, and the key input names the place to start.

    Keys of the interior dictionary become button labels.
    Their associated values are keys into the outer dictionary showing where to look if that button is used. If the value of an interior dictionary is not a key in the outer dictionary it is textwrapped and displayed in a Text window as a description or recipe. I hope this description, plus trying the program, plus looking at the code is sufficient description.

    What are the ingredients to loop soup ?

    Code:
    try:
        import tkinter
    except:
        import Tkinter as tkinter
    
    import textwrap
    
    def gui(key, data, root):
        if key in data:
            Menu(key, data, root)
        else:
            text(key, root)
    
    def text(message,root,width=30):
        wrapped_message = textwrap.fill(message,width=width)
        master = tkinter.Toplevel(root)
        w = tkinter.Text(master,width=width,height=1+wrapped_message.count('\n'))
        w.pack(side=tkinter.TOP)
        w.insert(tkinter.END,wrapped_message)
        tkinter.Button(master,text='quit',command=master.destroy).pack(side=tkinter.TOP)
    
    def Menu(key, data, root):
        master = tkinter.Toplevel(root)
        for (k,v,) in data[key].items():
            tkinter.Button(master,text=k,command=lambda key=v,data=data,root=root:gui(key,data,root)).pack(side=tkinter.TOP)
        tkinter.Button(master,text='quit',command=master.destroy).pack(side=tkinter.TOP)
    
    def main(key,data):
        root = tkinter.Tk()
        tkinter.Button(root,text='master kill switch',font=('Helvetica', '16'),
                       fg='red',bg='black',
                       activebackground='red',activeforeground='black',
                       command=root.destroy).pack(side=tkinter.TOP)
        gui(key,data,root)
        root.mainloop()
    
    
    if '__main__' == __name__:
    
        menu = dict(
            top=dict(breakfast='brk',lunch='lnh',dinner='unfinished'),
            brk=dict(eggs='eggs',waffles='Use pancake recipe with extra oil.  Beat the egg whites, fold them into the batter..  Toast nuts pieces in iron, then add batter.'),
            lnh=dict(sandwich='pbj, fluffernutter, peanut butter and dill pickle on rye---remember the lettuce!',soup='soup',sides='fries, slaw'),
            soup = {'beef knuckle':'find a stalwart bull.  Slaughter.  ... ','loop soup':'top'},
            eggs = {'ez over':'grease grill, splatter egg, flip gently.', 'scrambled':'mix eggs with a bit of milk, scramble on grill with cottage cheese and dill weed'}
            )
    
        main(key = 'top', data = menu)
    [code]Code tags[/code] are essential for python code and Makefiles!
  10. #6
  11. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2013
    Posts
    4
    Rep Power
    0
    Magic!!! That code is perfect. Thanks! I'm studying it to try to figure it all out. I like your recipes + ingredient usage, now I want waffles.

    Loop soup will require you to hike to the Misty Mountains, where you will have to pick an equal number of loops, and spool. Boil for an hour so they connect, and voila! Loop soup. Add salt to taste.
  12. #7
  13. Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Feb 2005
    Posts
    610
    Rep Power
    65
    Another option, a little less 'dummkopfy', but far from finished ...
    Code:
    ''' ttk_notebook3.py
    exploring the Tkinter expansion module ttk notebook
    included with Python version 2.7.3 and higher
    
    start of a recipe book?
    '''
    
    try:
        # Python27
        import Tkinter as tk
        import ttk  
    except ImportError:
        # Python31 and higher
        import tkinter as tk
        import tkinter.ttk as ttk  
    
    def action1(event):
        """
        a combobox1 item has been selected, do some action
        """
        key = combo1.get()
        root.title(key) # test
        text = recipe_dict[key]
        label1['text'] = text
    
    def action2(event):
        """
        a combobox2 item has been selected, do some action
        """
        key = combo2.get()
        root.title(key) # test
        text = recipe_dict[key]
        label2['text'] = text    
    
    def action3(event):
        """
        a combobox3 item has been selected, do some action
        """
        key = combo3.get()
        root.title(key) # test
        text = recipe_dict[key]
        label3['text'] = text    
        
    # customize this ...
    recipe_dict = {
    'eggs': '''\
    boil 5 eggs for 10 minutes
    peal off shell and serve with mayo and toast''', 
    'pancakes': 'flour, egg, buttermilk', 
    'oatmeal': 'steelcut oats, water',
    'hamburger': '''\
    take 12 oz. ground beef, mix with salt, pepper, garlic powder,
    then form paddy and fry on griddle''', 
    'soup': 'noodles, chicken, salt', 
    'sandwich': 'bread, ham, mustard',
    'steak': '''\
    take 16 oz. beef sirloin steak, rub with salt and pepper
    then pan fry and serve with potatoes and squash''', 
    'liver': '''\
    4 slices of beef liver, bread lightly and pan fry
    serve with cooked onions and mashed potatoes''', 
    'pork': 'pork chop, pepper, fry'               
    }
        
            
    root = tk.Tk()
    # use width x height + x_offset + y_offset (no spaces!)
    root.geometry("%dx%d+%d+%d" % (500, 300, 100, 50))
    root.title('testing the ttk.Notebook')
    
    nb = ttk.Notebook(root)
    nb.pack(fill='both', expand='yes')
    
    # create a child frame for each page
    f1 = tk.Frame(bg='red')
    f2 = tk.Frame(bg='blue')
    f3 = tk.Frame(bg='green')
    
    # create the pages
    nb.add(f1, text='breakfast')
    nb.add(f2, text=' lunch ')
    nb.add(f3, text=' dinner ')
    
    # copy and paste page stuff with a few changes ...
    
    # put a combo box widget on child frame f1
    combo1 = ttk.Combobox(f1)
    # selected list of keys from recipe_dict
    bf_list = ['eggs', 'pancakes', 'oatmeal']
    combo1['values'] = bf_list 
    combo1.set(bf_list[0])
    combo1.pack(side='top', anchor='nw', padx=3, pady=5)
    combo1.bind('<<ComboboxSelected>>', action1)
    # add a label
    label1 = tk.Label(f1)
    label1.pack(side='top', anchor='nw', padx=3, pady=5)
    action1(None)
    
    # put a combo box widget on child frame f2
    combo2 = ttk.Combobox(f2)
    # selected list of keys from recipe_dict
    mz_list = ['hamburger', 'soup', 'sandwich']
    combo2['values'] = mz_list 
    combo2.set(mz_list[0])
    combo2.pack(side='top', anchor='nw', padx=3, pady=5)
    combo2.bind('<<ComboboxSelected>>', action2)
    # add a label
    label2 = tk.Label(f2)
    label2.pack(side='top', anchor='nw', padx=3, pady=5)
    action2(None)
    
    # put a combo box widget on child frame f3
    combo3 = ttk.Combobox(f3)
    # selected list of keys from recipe_dict
    dr_list = ['steak', 'liver', 'pork']
    combo3['values'] = dr_list 
    combo3.set(dr_list[0])
    combo3.pack(side='top', anchor='nw', padx=3, pady=5)
    combo3.bind('<<ComboboxSelected>>', action3)
    # add a label
    label3 = tk.Label(f3)
    label3.pack(side='top', anchor='nw', padx=3, pady=5)
    action3(None)
    
    root.mainloop()
    ... a lot of copy and paste code with minor changes.

    Comments on this post

    • b49P23TIvg agrees : Beautiful. My liver recipe includes words like "throw" and "run".
    Last edited by Dietrich; March 10th, 2013 at 09:51 AM.
    Real Programmers always confuse Christmas and Halloween because Oct31 == Dec25
  14. #8
  15. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Mar 2013
    Posts
    4
    Rep Power
    0
    I really like yours too- Thanks! I will be using these! (and figuring out how they work haha)

IMN logo majestic logo threadwatch logo seochat tools logo