CSC111 Lab 14 2015

From dftwiki3
Revision as of 14:32, 29 April 2015 by Thiebaut (talk | contribs) (Challenge #4: Controlling the Buttons with the Checkbox)
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()


  • 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

QuestionMark1.jpg


  • 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="Bye!", command=change1 )
    button1.pack()
    
    rootWindow.mainloop()


main()


  • Run your code.
  • Verify that clicking on the button makes the label change.



Challenge #2: Add a Second Button That Changes the Label, Too

QuestionMark2.jpg


  • Add or modify the second button, if you have it in your GUI, so that the first button changes the label to "Goodbye World!", and the second button changes the label to "Hello World!".



Placing Widgets in a Grid


  • place() is a very simple way to put the widgets on the GUI window. A more powerful option is to use grid(), which requires have organized all the widgets on paper first, and knowing where they should be relative to each other.
  • Let's put all three widgets (label, button1 and button2) on the same line. This corresponds of a grid with 1 row and 3 columns.
  • Only 3 lines have to change. They are shown below:


    label.grid( row=0, column=0 )

    button1.grid( row=0, column=1 )

    button2.grid( row=0, column=2 )


  • Make the modification and run your App. Do the 3 widgets display in a horizontal alignment?



Challenge #3: Reorganize the Widgets

QuestionMark3.jpg


  • Change the organization of the grid so that the label is between the two buttons.
  • When that works, change the organization of the grid so that the label is on the right hand side of the window.
  • Change the organization some more, so that the label is on a row by itself, and the two buttons are next to each other, on a row below the label.



Organizing the GUI as a Class


  • The need to make label a global variable is cumbersome. If we have many widgets, we may have to do this many times. It is much more efficient and elegant to use a class for holding all the widgets, and all the actions that are associated with them.


from tkinter import *
from tkinter import ttk

class GUI:
    def __init__( self, rootWindow ):
        self.label = ttk.Label( rootWindow, text="Hello World!" )
        self.label.grid( row=0, column=0 )

        self.button1 = ttk.Button( rootWindow, text="Hello",
                                   command=self.hello )
        self.button1.grid( row=0, column=1 )

        self.button2 = ttk.Button( rootWindow, text="Bye",
                                   command=self.bye )
        self.button2.grid( row=0, column=2 )
        
    def bye( self ):
        self.label.config( text = "Goodbye World!" )

    def hello( self ):
        self.label.config( text = "Hello World!" )
    
def main():
    global label
    rootWindow = Tk()

    gui = GUI( rootWindow )
    rootWindow.mainloop()


main()


Adding A Checkbox


  • A checkbox is a widget that has a box that the user can click to either turn it ON, or OFF.
  • A checkbox must be associated with a special object in the code, such that if the user changes the checkbox by clicking it, then that object will automatically change its value. Similarly, if we change the value of this object inside the Python code, then the checkbox should automatically show itself as checked or unchecked, depending on the value of the object.
  • This seems complicated. An example will illustrate the point.
  • Let's add a checkbox to your GUI. Add the code below to your constructor:


        # create an object to keep the value of the checkbox
        self.buttonsEnabled = IntVar()
        self.buttonsEnabled.set( 1 )

        # create a checkbox and associate it with the object above.
        self.check1 = ttk.Checkbutton( rootWindow, text="Enable", variable=self.buttonsEnabled )
        self.check1.grid( row=1, column=0 )


  • Note that to change the value of the buttonsEnable object, which is instantiated from the class IntVar, we use its set() method. To get the value of such an object, there is another method, called get(), that we could use.
  • Modify the bye() and hello() methods of your GUI class, as shown below:


    def bye( self ):
        self.label.config( text = "Goodbye World!" )
        print( "buttonsEnabled = ", self.buttonsEnabled.get() )

    def hello( self ):
        self.label.config( text = "Hello World!" )
        self.buttonsEnabled.set( 1-self.buttonsEnabled.get() )


  • Click on the Hello button a few times. Explain the behavior you are observing. If you don't get it, make sure to ask questions to the lab instructor or TA nearby.
  • Click on the Bye button a few times, and watch the console. The code above, and the behavior you observe should make sense.
  • Finally, click on the Enable check box to make it checked, or uncheckes, and then click on the appropriate button to see the contents of the self.buttonsEnabled object.




Challenge #4: Controlling the Buttons with the Checkbox

QuestionMark5.jpg


  • The real purpose of the checkbox, you will have probably guessed, is to control whether the buttons modify the label or not.
  • We want the buttons to change the label only when the checkbox is checked, and not change the label when the checkbox is unchecked.
  • Modify your GUI class so that you make it adopt this behavior.




Adding a Text Area


  • A text-area widget is a rectangular area that can act as a simple editor. Actually, Idle, which you are probably using to create the code for this lab, is written with TKinter, so the area where you are typing code is probably a text area widget.
  • Before adding the text area, make sure your 4 widgets (label, 2 buttons, checkbox) are organized in a grid, all on Row 0. You will add the text area on Row 1, and make it span all 4 columns.
  • Adding a text area is very simple. Add these lines to the constructor of your GUI class.


        self.text = Text( rootWindow, width=80, height=30, background="ivory" )
        self.text.grid( row=1, column=0, columnspan=4 )
  • Run your code. You should see a larger window than before. This is because it now contains a text area that can hold 80 characters across, and 30 lines of them.
  • Click on the ivory-colored block, and enter some text. Copy some text from some other window (this lab, for example) and paste it in the text-area of your GUI. Notice that without any coding, you have added a text editor to your application!


Clearing the Text Area


  • The text area is fully documented on this page. It is tricky to figure out how to access various lines. Fortunately, clearing the text area requires a simple command:


     self.text.delete(1.0, END)


  • Explanations:
  • 1.0 means Line 1, Column 0. TKinter numbers lines starting at 1, for some strange reason.
  • END is a special constant used by TKinter that means the end of the text in the text area. So delete(1.0, END) will actually clear the whole text area.



Solution Programs


2 Buttons, 1 Label, Pack


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 bye():
    global label
    label.config( text = "Goodbye World!" )

def hello():
    global label
    label.config( text = "Hello World!" )
    
def main():
    global label
    rootWindow = Tk()

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

    button1 = ttk.Button( rootWindow, text="Hello", command=hello )
    button1.pack()

    button2 = ttk.Button( rootWindow, text="Bye", command=bye )
    button2.pack()
    
    rootWindow.mainloop()


main()


2 Buttons, 1 Label, Grid


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 bye():
    global label
    label.config( text = "Goodbye World!" )

def hello():
    global label
    label.config( text = "Hello World!" )
    
def main():
    global label
    rootWindow = Tk()

    label = ttk.Label( rootWindow, text="Hello World!" )
    label.grid( row=0, column=0 )

    button1 = ttk.Button( rootWindow, text="Hello", command=hello )
    button1.grid( row=0, column=1 )

    button2 = ttk.Button( rootWindow, text="Bye", command=bye )
    button2.grid( row=0, column=2 )
    
    rootWindow.mainloop()


main()


Enable CheckBox


from tkinter import *
from tkinter import ttk

class GUI:
    def __init__( self, rootWindow ):
        self.label = ttk.Label( rootWindow, text="Hello World!" )
        self.label.grid( row=0, column=0 )

        self.button1 = ttk.Button( rootWindow, text="Hello",
                                   command=self.hello )
        self.button1.grid( row=0, column=1 )

        self.button2 = ttk.Button( rootWindow, text="Bye",
                                   command=self.bye )
        self.button2.grid( row=0, column=2 )

        # create an object to keep the value of the checkbox
        self.buttonsEnabled = IntVar()
        self.buttonsEnabled.set( 1 )

        # create a checkbox and associate it with the object above.
        self.check1 = ttk.Checkbutton( rootWindow, text="Enable", variable=self.buttonsEnabled )
        self.check1.grid( row=1, column=0 )

    def bye( self ):
        if self.buttonsEnabled.get()==1:
            self.label.config( text = "Goodbye World!" )
        #print( "buttonsEnable = ", self.buttonsEnabled.get() )

    def hello( self ):
        if self.buttonsEnabled.get()==1:
            self.label.config( text = "Hello World!" )
        #self.buttonsEnabled.set( 1-self.buttonsEnabled.get() )
    
def main():
    global label
    rootWindow = Tk()

    gui = GUI( rootWindow )
    rootWindow.mainloop()


main()