Python Forum

Full Version: Window Not Appearing
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
For some reason, everything on this works except for MainWindow(). It adds the person to the tempfile, but the MainWindow never pops up. I get no errors, it just won't show me the window :/

[inline]
from Tkinter import *
import os
import Tkinter as ttk
from ttk import *

creds = 'tempfile.temp'

def NewPerson():
global nameE
global shoeSizeE
global roots

roots = Tk()
roots.title('New Person')
intruction = Label(roots, text='Enter Information Below\n')
intruction.grid(row=0, column=0, sticky=E)

nameL = Label(roots, text='Name: ')
shoeSizeL = Label(roots, text='Shoe Size: ')
nameL.grid(row=1, column=0, sticky=W)
shoeSizeL.grid(row=2, column=0, sticky=W)

nameE = Entry(roots)
shoeSizeE = Entry(roots)
nameE.grid(row=1, column=1)
shoeSizeE.grid(row=2, column=1)

signupButton = Button(roots, text='Create', command=StorePerson)
signupButton.grid(columnspan=2, sticky=W)
roots.mainloop()

def StorePerson():
with open(creds, 'w') as f:
f.write(nameE.get())
f.write('\n')
f.write(shoeSizeE.get())
f.close()

roots.destroy()
MainWindow()

def MainWindow():

root = Tk()
root.title("AWD ShoeBot")

with open(creds) as f:
data = f.readlines()
name = data[0].rstrip()

mainframe = Frame(root)
mainframe.grid(column=0,row=0, sticky=(N,W,E,S) )
mainframe.columnconfigure(0, weight = 1)
mainframe.rowconfigure(0, weight = 1)
mainframe.pack(pady = 100, padx = 100)

tkvar = StringVar(root)

choices = { name }
tkvar.set(name)

popupMenu = OptionMenu(mainframe, tkvar, *choices)
Label(mainframe, text="Choose a Person").grid(row = 1, column = 1)
popupMenu.grid(row = 2, column =1)

def change_dropdown(*args):
print( tkvar.get() )

tkvar.trace('w', change_dropdown)

signupButton = Button(root, text='Create New Person', command=NewPerson)
signupButton.grid(columnspan=2, sticky=W)

root.mainloop()

if os.path.isfile(creds):
MainWindow()
else:
NewPerson()
[/inline]
It looks like you are using MainWindow before you define it? Also, not sure if this applies, but I think you might have to use Toplevel() instead of Tk() when making another window.
Side note: since you have a lot of code, it might be helpful to add some comments to it
Is this better? I don't think I called MainWindow() before I defined it, but I think you made that mistake cause I posted the code wrong XD (sorry about that) But yeah it just won't open the MainWindow() function, although it shows no errors. :/
Thanks for the help!

from Tkinter import *
import os
import Tkinter as ttk
from ttk import *

creds = 'tempfile.temp'

def MainWindow():

    root = Tk()
    root.title("AWD ShoeBot")

    with open(creds) as f:
        data = f.readlines()
        name = data[0].rstrip()
 
    mainframe = Frame(root)
    mainframe.grid(column=0,row=0, sticky=(N,W,E,S) )
    mainframe.columnconfigure(0, weight = 1)
    mainframe.rowconfigure(0, weight = 1)
    mainframe.pack(pady = 100, padx = 100)

    tkvar = StringVar(root)

    choices = { name }
    tkvar.set(name)
 
    popupMenu = OptionMenu(mainframe, tkvar, *choices)
    Label(mainframe, text="Choose a Person").grid(row = 1, column = 1)
    popupMenu.grid(row = 2, column =1)

    def change_dropdown(*args):
        print( tkvar.get() )

    tkvar.trace('w', change_dropdown)
 
    signupButton = Button(root, text='Create New Person', command=NewPerson)
    signupButton.grid(columnspan=2, sticky=W)

    root.mainloop()

def NewPerson():
    global nameE
    global shoeSizeE
    global roots

    roots = Tk()
    roots.title('New Person')
    intruction = Label(roots, text='Enter Information Below\n')
    intruction.grid(row=0, column=0, sticky=E)

    nameL = Label(roots, text='Name: ')
    shoeSizeL = Label(roots, text='Shoe Size: ')
    nameL.grid(row=1, column=0, sticky=W)
    shoeSizeL.grid(row=2, column=0, sticky=W)

    nameE = Entry(roots)
    shoeSizeE = Entry(roots)
    nameE.grid(row=1, column=1)
    shoeSizeE.grid(row=2, column=1)

    signupButton = Button(roots, text='Create', command=StorePerson)
    signupButton.grid(columnspan=2, sticky=W)
    roots.mainloop()

def StorePerson():
    with open(creds, 'w') as f:
        f.write(nameE.get())
        f.write('\n')
        f.write(shoeSizeE.get())
        f.close()

    roots.destroy()
    MainWindow()

if os.path.isfile(creds):
    MainWindow()
else:
    NewPerson()
you are trying to use grid and pack on the same frame (mainframe) that's a no no.
Remove either the grid or the pack.
One but not both.
Also, change the def for mainwindow to:
def MainWindow(creds)
# and then call like:
MainWindow('tempfile.temp')
also it's better to use naming like main_window (PEP8) rather than camel case
(Sep-18-2017, 10:32 PM)Larz60+ Wrote: [ -> ]you are trying to use grid and pack on the same frame (mainframe) that's a no no.
Remove either the grid or the pack.
One but not both.
Also, change the def for mainwindow to:
def MainWindow(creds)
# and then call like:
MainWindow('tempfile.temp')
also it's better to use naming like main_window (PEP8) rather than camel case

All of your suggestions helped and made it work! Thanks!

I was also wondering one more thing though, do you have any recommendations on how to be able to add more people in my program? If not it's fine :P
Thanks!
when you open your save file, use mode 'a' (append)
Now you can just add new people to the end of the file.
It would be even better to use json format, which you can load,
append in memory, and rewrite when done.
There are some good tutorials on json
Here's one I like: https://pymotw.com/3/json/

I'll play with your code a bit and get back soon
(Sep-18-2017, 11:29 PM)Larz60+ Wrote: [ -> ]when you open your save file, use mode 'a' (append)
Now you can just add new people to the end of the file.
It would be even better to use json format, which you can load,
append in memory, and rewrite when done.
There are some good tutorials on json
Here's one I like: https://pymotw.com/3/json/

I'll play with your code a bit and get back soon

Thank you so much! :D
I'm calling it quits for the day.
Almost done with changes, pick up later
Ok,

Hope you don't mind, but I kind of got carried away with this.
All seems to work, except for some reason the entry portion is sitting in the
middle of the right frame, rather than at top.
I also didn't clear entry out after a new person was entered.
I'll leave that for you to finish.
Here's what I did:
import tkinter as tk
import os
import json
import tkinter.ttk as ttk


class ShoeBot:
    def __init__(self, parent, filename):
        self.roots = parent
        self.roots.title('AWD ShoeBot')
        # self.roots.geometry('400x200+10+10')
        self.treeheight = 19
        self.filename = os.path.abspath(filename)
        self.fp = None
        self.people = {}
        self.person_added = False
        self.this_person = None
        self.name = tk.StringVar()
        self.shoe_size = tk.StringVar()
        self.build_gui()
        self.load_tree()

    def build_gui(self):
        self.create_main_frame()
        self.create_left_frame()
        self.create_right_frame()
        self.create_bottom_frame()
        self.create_tree()
        self.create_user_dialog()
        self.create_statusbar()
        self.roots.protocol("WM_DELETE_WINDOW", self.on_delete)

    def create_main_frame(self):
        self.main_frame = tk.Frame(self.roots, relief=tk.RAISED)
        self.main_frame.grid(row=0, column=0, sticky='nseww')
        self.main_frame.columnconfigure(0, weight=1)
        self.main_frame.rowconfigure(0, weight=1)
        self.main_frame.pack(pady=5, padx=5)

    def create_left_frame(self):
        self.left_frame = tk.Frame(self.main_frame, relief=tk.SUNKEN)
        self.left_frame.grid(row=0, rowspan=self.treeheight, column=0, columnspan=2, sticky='ns')

    def create_right_frame(self):
        self.right_frame = tk.Frame(self.main_frame, relief=tk.SUNKEN)
        self.right_frame.grid(row=0, rowspan=self.treeheight, column=2, columnspan=10, sticky='e')

    def create_bottom_frame(self):
        self.bottom_frame = tk.Frame(self.main_frame, relief=tk.SUNKEN)
        self.bottom_frame.grid(row=self.treeheight + 1, column=0, columnspan=11, sticky='ew')

    def create_tree(self):
        treestyle = ttk.Style()
        treestyle.configure('Treeview.Heading', foreground='white',
                            borderwidth=2, background='SteelBlue',
                            rowheight=self.treeheight,
                            height=3)

        self.tree = ttk.Treeview(self.left_frame,
                                 height=self.treeheight,
                                 padding=(2, 2, 2, 2),
                                 columns='Name',
                                 selectmode="extended")

        self.tree.column('#0', stretch=tk.YES, width=180)
        self.tree.tag_configure('monospace', font='courier')
        treescrolly = tk.Scrollbar(self.left_frame, orient=tk.VERTICAL,
                                   command=self.tree.yview)
        treescrolly.grid(row=0, rowspan=self.treeheight, column=1, sticky='ns')

        treescrollx = tk.Scrollbar(self.left_frame, orient=tk.HORIZONTAL,
                                   command=self.tree.xview)
        treescrollx.grid(row=self.treeheight + 1, column=0, columnspan=2, sticky='ew')
        self.tree.configure(yscroll=treescrolly)
        self.tree.configure(xscroll=treescrollx)
        self.tree.grid(row=0, rowspan=self.treeheight, column=0, sticky='nsew')
        self.tree.bind('<Double-1>', self.name_selected)

    def load_tree(self):
        if os.path.isfile(self.filename):
            self.load_data()
            for person, value in self.people.items():
                self.tree.insert('', 'end', text='{}'.format(person))
                # print('person: {}, value: {}'.format(person, value))

    def create_user_dialog(self):
        self.intruction = tk.Label(self.right_frame, text='Enter Information Below\n')
        self.intruction.grid(row=0, column=0, sticky='nse')
        self.nameL = tk.Label(self.right_frame, text='Name: ')
        self.shoeSizeL = tk.Label(self.right_frame, text='Shoe Size: ')

        self.nameL.grid(row=1, column=0, sticky='w')
        self.shoeSizeL.grid(row=2, column=0, sticky='w')

        self.nameE = tk.Entry(self.right_frame, textvariable=self.name)
        self.shoeSizeE = tk.Entry(self.right_frame, textvariable=self.shoe_size)
        self.nameE.grid(row=1, column=1)
        self.shoeSizeE.grid(row=2, column=1)

        signupButton = tk.Button(self.right_frame, text='Create', command=self.add_person)
        signupButton.grid(row=4, column=0, columnspan=2, sticky='w')

    def create_statusbar(self):
        self.sb = tk.Frame(self.bottom_frame)
        self.sb.grid(row=0, column=0, sticky='nsew')

    def on_delete(self):
        if self.person_added:
            self.save_data()
        self.roots.destroy()

    def load_data(self):
        with open(self.filename) as fp:
            self.people = json.load(fp)

    def save_data(self):
        with open(self.filename, 'w') as fo:
            json.dump(self.people, fo)

    def add_person(self):
        name = self.name.get()
        shoesize = self.shoe_size.get()
        self.people[name] = {'shoesize': shoesize}
        self.tree.insert('', 'end', text='{}'.format(name))
        self.person_added = True

    def name_selected(self, event):
        curitem = self.tree.focus()
        nidx = self.tree.item(curitem)
        name = nidx['text']
        shoesize = self.people[name]['shoesize']
        print('You selected {} who wears size {} shoe'.format(name, shoesize))
        # do stuff with selected person


    def find_person(self):
        try:
            person = self.name.get()
            self.this_person = self.people[person]
            print('found {} shoesize: {}'.format(self.this_person[name], self.this_person[name]['shoesize']))
        except:
            'Adding {} shoesize: {}'.format(self.name.get(), self.shoe_size.get())
            self.add_person()
            self.this_person = self.people[person]
        self.name.set('')
        self.shoe_size.set('')
        return self.this_person


def main():
    root = tk.Tk()
    sb = ShoeBot(root, filename='PeopleFile.json')
    root.mainloop()

if __name__ == '__main__':
    main()
Screenshot:
[attachment=246]
Sorry this is more than you asked for, I was on a roll.
please PM very sparingly.
It's OK to share with the forum.

As to your questions:
  • delete person -- I'll add this for you, but may not get to it for a while.
         basically, to delete from a dictionary, you use del dictname[key]
  • to prevent others from seeing results, you can add a password see: https://www.reddit.com/r/Python/comments...made_easy/
Pages: 1 2