CSC111 Lab 14 2015

From dftwiki3
Revision as of 12:26, 29 April 2015 by Thiebaut (talk | contribs) (Created page with "--~~~~ ---- =<center>TK Lab</center>= <br /> <bluebox> This lab covers TKinter on Python 3.X. A very good tutorial on TK can be found on Lynda.com. </bluebox> <br /> =TK Sk...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

--D. Thiebaut (talk) 13:26, 29 April 2015 (EDT)


TK Lab


This lab covers TKinter on Python 3.X. A very good tutorial on TK can be found on Lynda.com.


TK Skeleton


  • Create a new program called tkSkel0.py with the code below. You should work in Idle, as this will automatically make tkinter and ttk findable for Python.


from tkinter import *
from tkinter import ttk

 
    
def main():
    global label
    rootWindow = Tk()

    label = ttk.Label( rootWindow, text="Hello World!" )
    label.pack()

    rootWindow.mainloop()

main()


  • Run the program. Be careful, as this will create a tiny window on your screen, which may not be easily visible. But it should be there!
  • Congratulations. This is the "Hello World!" version of Python using the TKinter graphics environment.


Adding a Button


  • Now try adding some more code to your application:


from tkinter import *
from tkinter import ttk
    
def main():
    rootWindow = Tk()

    label = ttk.Label( rootWindow, text="Hello World!" )
    label.pack()

    button1 = ttk.Button( rootWindow, text="Change Label" )
    button1.pack()
    
    rootWindow.mainloop()

main()


  • Run the code. Observe that a new button will have appeared. Click on the button a few times. Why is it not doing anything?
  • If your answer is that we haven't define an action for the button, you are absolutely right!
  • Let's add a new function to the program, and "attach" it to the button.


from tkinter import *
from tkinter import ttk


def change():
    print( "change function called" )
    
def main():
    global label
    rootWindow = Tk()

    label = ttk.Label( rootWindow, text="Hello World!" )
    label.pack()

    button1 = ttk.Button( rootWindow, text="Change Label", 
                                    command=change )
    button1.pack()
    
    rootWindow.mainloop()


main()