CSC111 Lab 14 2015
--D. Thiebaut (talk) 13:26, 29 April 2015 (EDT)
Contents
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()
- Run your code again, and verify that when you click the button, something gets printed in the console.
- Using the console is not necessarily something we want to do with GUI applications, but, in this case, the console is a good way to debug our program and verify that it works as expected.
Challenge #1: Add a Second Button |
- Add a second button to your GUI. Call it button2.
- Add a new function and make the new button activate this function. Your new function will print some simple string on the console. Make sure the string and the function are different from the already defined change function, and the string it prints.
Button Changing The text of the Label
- Let's make the button change the text of the label when it (the button) is clicked:
from tkinter import * from tkinter import ttk label = None # this variable will hold the label created by the GUI, and will be accessible # by the change1() function. def change1(): global label label.config( text = "Goodbye World!" ) def main(): global label rootWindow = Tk() label = ttk.Label( rootWindow, text="Hello World!" ) label.pack() button1 = ttk.Button( rootWindow, text="Change Label", command=change1 ) button1.pack() rootWindow.mainloop() main()
- Run your code.
- Verify that clicking on the button makes the label change.