You are on page 1of 2

BenWoodfield

TkinterGUIBasics

FirstTkinterGUI/AsimpleWindow
Ok,soifyouopenupPython,andopenupanEditwindow(forlongercodewriting)
ifyoutypeinthisexactlyyoushouldseeasimpleGUI:
(NOTEIfyouareusinganyPython2version,youwillneedtorefertotkinterwithaCapitolT
TkintersobelowisforPython3,forpython2youtype:from Tkinter import * )
from tkinter import *
top = Tk()
top.minsize(400,400)
top.mainloop()

Nowaftereveryexample,SAVEandthenRUNyourcode.Onceyouhavesavedityoucanselect
Runfromthemenu,orhitF5ifyouhavemanywindowsopen,yoursmallnewprogrammaybe
lostbehindothers.
Iwillexplainthiscodelinebyline:

from tkinter import*ImportsthepartsofTkinterthatweneedtomakethisGUI.I


donotknowexactlywhatthe*imports,butifyoujusttype import tkinteryouwill
belimitedtowhatfeaturesyoucanuse.NowifyouweretoimportEverythingintoPython
itwouldstarttorunalittleslowly.

top = Tk() :Tk()isthenameforyourROOTwindow.Itisthemainwindowthatyou


willseewhenyouruntheprogram.Youcanhavemorewindows(subwindows)butthis
willalwaysbethemainone.SomepeoplecallitaParentwindow.Ihavecalledittopas
itisthetoplevelwindow.Youcanreplacetopforanywordname,justkeepitsimpletouse
andifyouchangeitinthefutureyouwillneedtochangeeverythingelsenamedtop.

top.minsize(400,400):ThislinetellsPythonthatwewanttomakethewindowa
certainsize.400x400isafairlystandardsize.ThetwonumbersrepresentWIDTHand
HEIGHT.YoucanchangethesevaluesandplayaroundwiththesizetosuityourGUI.If
weREMOVEthisline,youwillgetaverysmallsquarewindow!Thereareotherwaysto
setthewidthandheight,butfornowthisisthesimplestwaytoexplain.

top.mainloop() :Thisisaloopthatmakesyourprogramrun.WithoutthislinePython
willnotmaketheGUIwindowappear.ThisloopmakesPythondisplayyourGUIwindow
untiltoldnotto(untilyoucloseit)

WhenyourunthisprogramfromPythonyoushouldseeasmallgreywindowwithatitlecalled
TkonthetopbaroftheGUI.
Ifyouhaveanyproblems,sendmeacopyofthespecificerror,ortrytotakeascreenshotofthe
Errormessage,andwewilltryandresolveitfromthere.
NEXT:ThenextdocumentwillbeaTkinterGUIverysimilartothisfirstone,butwewilladd
somefeatures.WewillchangethetitleandaddaQUITbuttontoexittheGUIcleanlyandeasily
withoutanyerrors!

You might also like