Tkinter

Objectives

  • Install TkInter
  • Getting started with TkInter
    • Adding a Widget

Languages

Device Interfaces

User Interfaces

Hello TkInter

Before you start, import tkinter.

from tkinter import *

In TkInter, everything is a widget. There is a button widget, a text widget and a frame widget. At the beginning, you are going to have a root widget like the window. So let’s create the window called root.

from tkinter import *

root = Tk()

After creating a window, now you want to add a label widget.Create a Label widget with the text “Hello World!” inside the window root.

from tkinter import *

root = Tk()

myLabel = Label(root, text="Hello World!")

The Window you created earlier doesn’t change. You just created a Label widget but you haven’t added it to the window yet. There are a couple way to put it on the screen. The first one is using pack.

from tkinter import *

root = Tk()

# Creating a Label Widget
myLabel = Label(root, text="Hello World!")

# Showing it onto the screen
myLabel.pack()

In the programming, we usually have a looping function to sense the changes, such as to know if you are moving your mouse towards something. There there must a constant loop till something happend.

from tkinter import *

root = Tk()

# Creating a Label Widget
myLabel = Label(root, text="Hello World!")

# Showing it onto the screen
myLabel.pack()

root.mainloop()

Title

from tkinter import *

root = Tk()
root.title('Fab Lab O Shanghai')

root.mainloop()

Grid System

Think that your program is like a grid. It has columns and rows.

from tkinter import *

root = Tk()

# Creating a Label Widget
myLabel1 = Label(root, text="Hello World!")
myLabel2 = Label(root, text="Welcome to Fab Lab O Shanghai")

# Showing it onto the screen
myLabel1.grid(row=0, column=0)
myLabel2.grid(row=1, column=0)

root.mainloop()

Buttons

from tkinter import *

root = Tk()

# Creating a button didget
myButton = Button(root, text="Click me")

# Showing it onto the screen
myButton.pack()

root.mainloop()

State= DISABLED

from tkinter import *

root = Tk()

# Creating a button Widget
myButton = Button(root, text="Click me", state =DISABLED)

# Showing it onto the screen
myButton.pack()

root.mainloop()

Button Size

from tkinter import *

root = Tk()

# Creating a button Widget
myButton = Button(root, text="Click me", padx=50, pady=50)

# Showing it onto the screen
myButton.pack()

root.mainloop()

Create a Dunction With a Button

from tkinter import *

root = Tk()

def myClick():
    myLabel = Label(root, text="Look! I click a button!!")
    myLabel.pack()


# Creating a Label Widget
myButton = Button(root, text="Click me", command=myClick, padx=50, pady=50)

# Showing it onto the screen
myButton.pack()

root.mainloop()

Input Fields

Hello Entry Widget

from tkinter import *

root = Tk()
# Creating an entry Widget
e = Entry(root)

# Showing it onto the screen
e.pack()

root.mainloop()

Insert

from tkinter import *

root = Tk()

# Creating an entry widget
e = Entry(root)
e.insert(0, "Enter Your Name: ")
e.pack()


root.mainloop()

Entry, Label and Button

from tkinter import *

root = Tk()



def myClick():
    myLabel = Label(root, text="Hello "+ e.get())
    myLabel.pack()

# Creating an entry widget
e = Entry(root)
e.pack()

# Creating a Label widget
myButton = Button(root, text="Click me", command=myClick)
myButton.pack()

root.mainloop()

Canvas Widget

ffrom tkinter import *

root = Tk()
my_canvas = Canvas(root, width=300, height=200)
my_canvas.pack()

root.mainloop()

Background

from tkinter import *

root = Tk()
my_canvas = Canvas(root, width=200, height=200, background='red')

root.mainloop()

Canvas Text Object

You can display one or more lines of text on a canvas C by creating a text object:

create_text(x, y, fill, font, text)

id = C.create_text(x, y, option, ...)

This returns the object ID of the text object on canvas C.

from tkinter import *

window = 200 #window size

root = Tk()
my_canvas = Canvas(root, width=window, height=window, background='white')
my_canvas.create_text(.5*window,.5*window,text="read",font=("Helvetica", 24),tags="text",fill="#0000b0")
my_canvas.pack()

root.mainloop()

Canvas Rectangle Objects

Each rectangle is specified as two points: (x0, y0) is the top left corner, and (x1, y1) is the location of the pixel just outside of the bottom right corner.

    id = C.create_rectangle(x0, y0, x1, y1, option, ...)
from tkinter import *

window = 200 #window size

root = Tk()
my_canvas = Canvas(root, width=2*window, height=window, background='white')
my_canvas.create_rectangle(window,0,2*window,window, tags='rect', fill='#b00000')
my_canvas.pack()

root.mainloop()

Canvas Line Objects

In general, a line can consist of any number of segments connected end to end, and each segment can be straight or curved. To create a canvas line object on a canvas C, use:

id = C.create_line(x0, y0, x1, y1, ..., xn, yn, option, ...)

The line goes through the series of points (x0, y0), (x1, y1), … (xn, yn). Options include:

from tkinter import *

window = 200 #window size

root = Tk()
my_canvas = Canvas(root, width=2*window, height=window, background='white')
my_canvas.create_line(0, 0.5*window, 2*window, 0.5*window, fill='#b00000')
my_canvas.pack()

root.mainloop()

Item Configure

from tkinter import *

window= 200
colour_state = 0

root = Tk()



def myClick():
    global colour_state

    if (colour_state==0):
        my_canvas.itemconfigure('rect', fill="#b00000")
        colour_state =1
    else:
        my_canvas.itemconfigure('rect', fill="#0000b0")
        colour_state =0
    print(("state: {}").format(colour_state))
    my_canvas.pack()

# Creating a canvas widget
my_canvas = Canvas(root, width=window, height=window, background='white')
my_canvas.create_rectangle(0,0,window,window, tags='rect', fill='#b00000')
my_canvas.pack()

# Creating a button widget
myButton = Button(root, text="Click me", command=myClick, padx=50, pady=50)
myButton.pack()

root.mainloop()

- Reference: Python global, local and nonlocal variables

After

after(delay_ms, callback=None, *args)

This method regirsters a callback function that will be called after a given number of milliseconds.

Hello Button

Neil’s starter code display the raw data that is coming in from a PCB board. In this section, we are playing with Tkinter to do some graphics and show the button click state. We will learn how exatcly the graphics works.

Microcontroller

/*
Turn on LED when the button is pressed
*/

int LED = 13; // the pin for the LED
int Button = 7; // the input pin where the push button is connected
int val = 0; // val will be used to store the state of the input pin
int old_val =0; 
int state= 0;


void setup() {
  // put your setup code here, to run once:
  pinMode(LED, OUTPUT) ; // tell Arduino is an output
  pinMode(Button, INPUT); // Button is an input

  Serial.begin(9600);
  Serial.println("Hello!");

}

void loop() {
  // put your main code here, to run repeatedly:
  val = digitalRead(Button); // read input value and store it

  Serial.println(state);
  delay(100);


  //check if the button is pressed ( input is HIGH) and change the state
  if((val== HIGH)&&(old_val == LOW)){
    state=1-state;
  }

  old_val =val;

  // check whether the input is HIGH (button is pressed)
  if(state==1){ 
    digitalWrite(LED, HIGH);
    // turn the LED on
  }else{
    digitalWrite(LED, LOW);
    // turn the LED off
  }


}

Python

#
# hello.button.py
#
# button sensor detector hello-world
#
# Neil Gershenfeld 11/16/15
# (c) Massachusetts Institute of Technology 2015
#
# modified: Marcello Tania
#
# This work may be reproduced, modified, distributed,
# performed, and displayed for any purpose. Copyright is
# retained and must be preserved. The work is provided
# as is; no warranty is provided, and users accept all 
# liability.
#

from tkinter import *
import serial

WINDOW = 200 # window size

def idle(parent,canvas):
    global filt,eps
    #
    # idle routine
    #
    char = ser.readline()
    char = str(char).replace("b", "").replace("\\r", "").replace("\\n", "").replace("'", "")
    print("arduino:{}".format(char))


    if (char == '1'):
        x = 1
        text = 'button'
        canvas.itemconfigure("rect",fill="#b00000")
        canvas.itemconfigure("text",text="on")
    else:
        x = 0
        text = 'off'
        canvas.itemconfigure("rect",fill="#0000b0")
        canvas.itemconfigure("text",text="off")


    canvas.update()
    parent.after_idle(idle,parent,canvas)


#
# open serial port
#

ser = serial.Serial('/dev/cu.usbserial-14140',9600)
ser.setDTR()
ser.flush()
#
# set up GUI
#
root = Tk()
root.title('hello.HC-SR501.py (q to exit)')
root.bind('q','exit')
canvas = Canvas(root, width=2*WINDOW, height=WINDOW, background='white')
canvas.create_text(.5*WINDOW,.5*WINDOW,text="read",font=("Helvetica", 24),tags="text",fill="#0000b0")
canvas.create_rectangle(WINDOW,0,2*WINDOW,WINDOW, tags='rect', fill='#b00000')
canvas.pack()
#
# start idle loop
#
root.after(100,idle,root,canvas)
root.mainloop()