Skip to main content

Gooey GUIs ,tkinter ,Label Tricks, Let's Talk About Text Baby,It All Adds Up,Packing

 Gooey GUIs

DISCLAIMER: As the title states, this can get gooey. TKinter totally sucks - if you'd rather move on to something more fun, click "mark lesson as complete" and move on to Day 70 to get back to the good stuff.
It's time to bring our programs into the early 90s as we learn how to create a Graphical User Interface (GUI) with a Python library called tkinter.

 
tkinter


tkinter is one of the more popular Python GUI libraries.
👉 When you start a tkinter project, you get some boilerplate, or starter code. 

import tkinter as tk
window = tk.Tk()
window.title("Hello World") # Sets the name of the window in the border
window.geometry("300x300") # Sets the size of the window in pixels
hello = tk.Label(text = "Hello World") # Creates a text box
hello.pack() # 'pack' places the element on the screen
button = tk.Button(text = "Click me!") # Creates a button
button.pack()
tk.mainloop() 
This code will produce a window that looks like this:


Play around with the size of the window to see the effect of changing the dimensions.

Label Tricks

👉 We can also use variables to pass strings into labels like this:

label = "Hey there world"
hello = tk.Label(text = label) 

👉 Now I'm going to use a subroutine that changes the text in the label when I click the button.

window = tk.Tk()
window.title("Hello World") 
window.geometry("300x300") 
label = "Hey there world"
def updateLabel():
  label = "Bye world!"
  hello["text"] = label 
  # Subroutine that updates the text in the label.
hello = tk.Label(text = label) 
hello.pack() 
button = tk.Button(text = "Click me!", command = updateLabel) # Calls the updateLabel subroutine when the button is clicked
button.pack()
tk.mainloop() 

👉 Let's try the same trick, only this time the label contains a number which increments with every button click. For this I need to use a global label variable
.
window = tk.Tk()
window.title("Hello World") 
window.geometry("300x300") 
label = 0 # Sets the starting label value to 0
def updateLabel():
  global label # Uses the values in the label variable
  label += 1 # Adds one to the value in the label
  hello["text"] = label 
  
hello = tk.Label(text = label) 
hello.pack() 
button = tk.Button(text = "Click me!", command = updateLabel) # Calls the updateLabel subroutine when the button is clicked
button.pack()
tk.mainloop() 
Adding Text
Let's Talk About Text Baby

We can add text boxes to our windows using the entirely obvious text command.
👉 Here's the code you need in isolation: 
text = tk.Text(window ,height=1, width = 50)
# Three arguments, name of the window to place the text box in, height & width.
text.pack 
👉 And here it is in context. 
window = tk.Tk()
window.title("Hello World") 
window.geometry("300x300") 
label = 0
def updateLabel():
  global label
  label += 1 
  hello["text"] = label 
  
hello = tk.Label(text = label) 
hello.pack() 
button = tk.Button(text = "Click me!", command = updateLabel) 
button.pack()
text = tk.Text(window ,height=1, width = 50)
text.pack
tk.mainloop()

This gives us a window with a text box like this:


It All Adds Up


Let's make our program add the number in the text box to the number in the label when the button is pressed.


👉 To do this, we need to change the updateLabel subroutine. Here's the code in isolation:


def updateLabel():
  global label
  number = text.get("1.0","end") # Gets the number from the text box (starting at the first position and going to the end.) and stores in the number variable
  number = int(number) #Casts to an integer. I've done this on a separate line to prevent the line above getting too complex, but you can combine the two.
  label += number # Adds the number from the text box to the one in the label.
  hello["text"] = label 
Placing Items
Our window does look a bit odd, doesn't it? Why have the button above the text box?


👉 We can simply change the order by defining the text box before the button in

 the code: window = tk.Tk()
window.title("Hello World") 
window.geometry("300x300") 
label = 0
 def updateLabel(): 
  global label
  number = text.get("1.0","end") 
  number = int(number) 
  label += number
  hello["text"] = label 
  
hello = tk.Label(text = label) 
hello.pack() 
text = tk.Text(window ,height=1, width = 50)
text.pack
button = tk.Button(text = "Click me!", command = updateLabel) 
button.pack()
tk.mainloop() 



Packing

We can add arguments to pack() to control the position of items in the window. Again, I'm just showing the relevant lines of code in these examples.


👉 Let's move the button to the bottom of the window.
button.pack(side=tk.BOTTOM)

👉 And the text box to the top to the left of the window.


text.pack(side=tk.LEFT)
You can also use TOP, RIGHT, CENTER to control location.
Unpacking
If we had several buttons, the default would be to put them one on top of another.
button = tk.Button(text = "Click me!",
command = updateLabel) 
button.pack()
button = tk.Button(text = "Another Button", command = updateLabel) 
button.pack()
button = tk.Button(text = "Last one", command = updateLabel) 
button.pack()



We can arrange them into a nicer grid layout, but to do this we have to completely remove pack and break the entire window into a grid.


👉 We then use row and column numbers (zero indexed remember) to place our elements. I've put the label in row 0, text box in row 1 and buttons in row 2.


window = tk.Tk()
window.title("Hello World") 
window.geometry("300x300") 
label = 0
def updateLabel():
  global label
  number = text.get("1.0","end") 
  number = int(number) 
  label += number
  hello["text"] = label 
  
hello = tk.Label(text = label).grid(row=0, column=1)
text = tk.Text(window ,height=1, width = 50).grid(row=1, column=1)
button = tk.Button(text = "Click me!", command = updateLabel).grid(row=2, column=0)
button = tk.Button(text = "Another Button", command = updateLabel).grid(row=2, column=1)
button = tk.Button(text = "Last one", command = updateLabel).grid(row=2, column=2)
tk.mainloop()





Comments

Popular posts from this blog

Web Scraping

 Web Scraping Some websites don't have lovely APIs for us to interface with. If we want data from these pages, we have to use a tecnique called scraping. This means downloading the whole webpage and poking at it until we can find the information we want. You're going to use scraping to get the top ten restaurants near you. Get started 👉 Go to a website like Yelp and search for the top 10 reastaurants in your location. Copy the URL.   url = "https://www.yelp.co.uk/search?find_desc=Restaurants&find_loc=San+Francisco%2C+CA%2C+United+States"   Import libraries 👉 Import your libraries. Beautiful soup is a specialist library for extracting the contents of HTML and helping us parse them. Run the Repl once your imports are sorted because we want the Beautiful Soup library to be installed (it'll run quicker this way). import requests from bs4 import BeautifulSoup url = "https://www.yelp.co.uk/search?find_desc=Restaurants&find_loc=San+Francisco%2C+CA%2C+Unite...

HTTP & Sessions

 HTTP & Sessions One of the main protocols (rules that govern how computers communicate) on the web is called HTTP. HTTP is what is known as a stateless protocol. This means that it doesn't 'remember' things. It's a bit like having a conversation with a goldfish. You can ask a question and get a reply, but when you ask a follow up question, the original has already been forgotten, as has who you are and what you were talking about. So if HTTP is stateless, how come my news site remembers to give me the weather for my home town, my preferred South American river based online store tells me when it's time to order more multivitamins, and I'm justifiably proud of my #100days success streak? The answer is......... Sessions Sessions are a way of storing files on your computer that allows a website to keep a record of previous 'conversations' and 'questions' you've asked. By using sessions, we can store this info about the user to access later....

Client/Server Logins

 Client/Server Logins Waaay back when we learned about repl.db, we mentioned the idea of a client/server model for storing data in one place and dishing it out to multiple users. This model is the way we overcome the issue with repl.db of each user getting their own copy of the database. Well, now we can use Flask as a webserver. We can build this client server model to persistently store data in the repl (the server) and have it be accessed by multiple users who access the website via the URL (the clients). Get Started Previously, we have built login systems using Flask & HTML. We're going to start with one of those systems and adapt it to use a dictionary instead. 👉 First, let's remind ourselves of the way the system works. Here's the Flask code. Read the comments for explanations of what it does: from flask import Flask, request, redirect # imports request and redirect as well as flask app = Flask(__name__, static_url_path='/static') # path to the static fil...