# Selecting a random student from a class list

This selects a random student from a class list, stored in a .ss file:

from Tkinter import Tk,Button,StringVar,Entry,Label
import random, tkFileDialog, tkMessageBox
root= Tk()
root.wm_title("Random Student Selector")
current=StringVar()
kids=[]
def choosekid():
try:
chosen=random.choice(kids)
except IndexError:
tkMessageBox.showinfo("Empty class", "You need to add a student")
current.set(chosen)
chooseKid=Button(root,text="Pick random student", command=choosekid)
chosenKid=Label(root,textvariable=current)
global kids
try:
except AttributeError:
tkMessageBox.showinfo("No file selected", "You need to select a file")
def savetofile():
stringToSave=""
for i in kids:
stringToSave=stringToSave+i+","
stringToSave=stringToSave[:-1]
savefile.write(stringToSave)
saveToFile=Button(root,text="Save a file",command=savetofile)
chooseKid.grid(row=1,column=1)
chosenKid.grid(row=1,column=0)
saveToFile.grid(row=2,column=1)
root.mainloop()

• first you should add empty lines before def to make it more readble. – furas Feb 12 '16 at 18:36
• you could organize code: imports (is separated lines), all your functions, rest (root = Tk(), etc.). – furas Feb 12 '16 at 18:48
• @furas try to avoid those kind of comments since they are appropriate for an answer. You can and should bunch up some like those and give an answer. – Bruno Costa Feb 12 '16 at 21:59

1. you don't use StringVars for your Entry widgets. Lots of tutorials seem to use them, but they are largely unnecessary
2. I like that you grouped all of your grid commands together.

Now, the things I think need improving:

from Tkinter import Tk,Button,StringVar,Entry,Label


Best practices suggest you import the whole library with a shorthand name such as tk. You then can reference each of the widgets by the short name to make it absolutely clear where the code is coming from. Otherwise, if you were to use both Tkinter and ttk widgets at some point, it becomes unclear if you're referencing a Tkinter widget or a ttk widget since they both export similar class names.

I suggest changing your import to this:

import Tkinter as tk


Then, change all references to Button to be tk.Button, etc. This extra little bit of typing will make your code much easier to read and maintain over time.

It's great that you grouped all of your grid statements together. However, the rest of your code is oddly interleaved. You have functions intermixed with code.

addKidName=Entry(...)
def choosekid(): ...


def addkid(): ...
def choosekid(): ...
def savetofile(): ...
...
...


If you use grid you should always do three things:

1) explicitly declare a sticky attribute for each widget 2) always use rowconfigure to give at least one row a positive, non-zero weight (even if it's an invisible row below all other rows) 3) always use columnconfigure to give at least one column a positive, non-zero weight (even if it's an invisible column to the right of all other columns)