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

Automate! Automate!

 Making this customizable 👉So how about making our search user customizable? In the code below, I have: Asked the user to input an artist (line 14) Tidied up their input (line 15) formatted the search URL as an fString that includes the artist (line 19) Here's tAutomate! Automate! We are so close. I can taste it, folks! Massive kudos on getting this far! Today's lesson, however, will work best if you have one of Replit's paid for features (hacker plan or cycles). Free plan Repls 'fall asleep' after a while. Automation kinda relies on the Repl being always on. If you have hacker plan or you've bought some cycles, then you can enable always on in the drop down menu that appears when you click your Repl name (top left).he code: This is important because when our repl is always running, it can keep track of time and schedule events. 👉 I've set up a simple schedule that prints out a clock emoji every couple of seconds. It works like this: Import schedule librar...

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....

Incoming!

 Incoming! Today, we're going to learn how to deal with data from forms in Flask. 👉 To start, I've added yesterday's HTML code for my form in main.py for you already. (You're welcome!) Go take a look! 👉 However, at the moment, the app.route() has no method associated with it, so I need to create a route for this page to receive the data. First, I need a new import: request. Then I create the app.route - I also need to add an extra argument to specify the methods being received. At the moment, that's just 'post', but it does need to be ALL CAPS - POST. Finally I define the process() subroutine that returns request.form 👉 Here's the new code on its own: from Flask import Flask, request app.route('/process', methods=["POST"]) def process():   return request.form 👉 And here it is as part of the whole code: from flask import Flask, request app = Flask(__name__) app.route("/process", methods=["POST"]) def process():   ...