Tkinter Flashcards
Import Tkinter
Create a window
Put text at the top of the box
Start the box
create root window
from tkinter import *
root = Tk()
root.title(“Welcome to GameShark”)
root.geometry(‘350x200’)
root.mainloop()
What is a label? Add one.
Don’t forget to add the function/class? that tells it where to go in the window!
create root window
A label is just a line of text.
from tkinter import *
root = Tk()
root.title(“Welcome to GameShark”)
root.geometry(‘350x200’)
lbl = Label(root, text = “GameShark has a bid DICK”)
lbl.grid()
root.mainloop()
Create a button, that when clicked, displays your text.
Don’t forget, you have to add code to tell the button and your label where to go now!
from tkinter import *
root = Tk()
root.title(“Welcome to GameShark”)
root.geometry(‘350x200’)
lbl = Label(root, text = “Gameshark is the BEST”)
lbl.grid()
txt = Entry(root, width=10)
txt.grid(column=1, row=0)
def clicked():
res = “you wrote “ + txt.get()
lbl.configure(text = res)
btn = Button(root, text = “Enter”, fg = “red”, command=clicked)
btn.grid(column=2, row=0)
root.mainloop()
Add a menu bar to your gui
add menu bar in root window
from tkinter import *
root = Tk()
root.title(“Welcome to Gameshark”)
root.geometry(‘350x200’)
#new item in menu bar labelled ‘New’
#add more items to the menu
menu = Menu(root)
item = Menu(menu)
item.add_command(label=’New’)
menu.add_cascade(label=’File’, menu=item
root.config(menu=menu)
lbl = Label(root, text = ‘Is GameShark the best?”)
lbl.grid()
#below that is where it’s placed
txt = Entry(root, width=10)
txt.grid(column=1, row=0)
def clicked():
res = "You wrote " + txt.get() lbl.configure(text = res)
btn = Button(root, text = “Click me”, fg = “red”, command=clicked)
btn.grid(column=2, row=0)
root.mainloop()
Create a background
if we don’t use pack, the next label will just go underneath the image
(toolkit interface)
from tkinter import *
root = Tk()
root.title(“GameShark”)
root.geometry(“500x500”)
lbl = Lable(root, text = “Hello, and welcome”, font=(‘Georgia’, 24,)
lbl.pack()
image_path = PhotoImage(file=r”C:\image\myimage.png”)
bg_image = Label(root, image=image_path)
# 0.5 means make image take up 50% of screen, 1 means the whole screen.
bg_image.place(relheight=0.5,relwidth=1)
Add Sounds
from tkinter import *
from playsound import playsound
def play():
playsound(r”C:\Users\joshc\Downloads\sword-sound-2-36274.mp3”)
root = Tk()
root.title(“GameShark”)
root.geometry(“500x500”)
menubar = Menu(root)
file_menu = Menu(menubar, tearoff=0)
file_menu.add_command(label=”Share with Brian”)
menubar.add_cascade(label=”Sharing”, menu=file_menu)
btn = Button(root, text=”Cut Noise”, command=play)
btn.grid(column=0,row=0)
root.config(menu=menubar)
root.mainloop()
What does pack mean?
Use it
Pack this in the first available spot. This is unsophisticated.
This will keep your text on the same spot no matter how you resize, which is nice.
lbl.pack()
How do you use grid
lbl1.grid(column=0,row=0)
lbl2.grid(row=1,column=5)
This will just put this in column one because it’s all relative to the first grid.
You could actually create this space one way doing something like this:
lbl3 = Label(root, text=””)
lbl3.grid(row=1, column=1)
Create a disabled button
Resize button
btn = Button(root, text=”click me”, state=DISABLED)
btn = Button(root, text=”click me”, padx=50, pady=50)
Create an entry widget and give it a width and height and give it a border
Put some default text inside your text box.
What function do you use to retrieve your entered text?
e = Entry(root, width=50,height=50,borderwidth=10)
e.insert(0, “Enter your name: “)
e.get()
Create a calculator
We’ll have a row of three numbers, so we’ll want to have the entry span those columns
Next time you do this, be sure to take the bits that you don’t know from the cal.py file and add them to flash cards so you’ll know the pieces of how to do this in the future.
https://www.youtube.com/watch?v=YXPyB4XeYLA
When placing an “Entry” widget, what option would you add if you wanted the box to span accross 3 buttons below it?
e.grid(row=0, column=0, columnspan=3, padx=10, pady=10)
Create a global variable if function is called.
def button_divide():
global math
math = “division”
Delete what’s in an entry field
e = Entry()
e.delete(0, END)
What option allows you to input an argument from a button onto a function?
command=lambda: button_click(1)
To resize a button, where do you add your padx and pady
Directly to the button, not the grid, the grid will just create space.
What is an Icon file called?
ICO which is just a PNG
Add an icon and an exit button
from tkinter import *
root = Tk()
root.title(“Gameshark”)
root.iconbitmap(r”C:\Users\joshc\Downloads\1805914c0f1e9c653168d23775b91be4.ico”)
button_quit = Button(root, text=”Exit Program”, command=root.quit)
button_quit.pack()
root.mainloop()
Add an image, because the built in image thingy only does two types of images
pip install Pillow
pip freeze (look for Pillow)
from PIL import ImageTk,Image
my_img = ImageTk.PhotoImage(Image.open(“aspen.png”)
my_label = Label(image=my_img)
my_label.pack
you also don’t need to specify directories if in same folder as program.
Say you have created and image but you want it removed when you click a button, what would you do to the label to make it work?
lbl.grid_forget()
If you wanted to create a label that said “image 1 of 3” that had a border that made it look sunken and have it situated on the right hand portion of the screen?
lbl = (root, text=”image 1 of 3”, bd=1, relief=SUNKEN, anchor=E)
What would you put if you wanted to stretch your label across your column span?
status.grid(row=2, column=0, columnspan=3, sticky=W+E)
Remember that columnspan is doesn’t stretch it just adjusts the placement, I believe.
Create a frame that surrounds a button
The only time you can use both frames and grids in your code is when working with frames and what they surround
frame = LabelFrame(root, text”this”, padx=5, pady=5)
frame.pack(padx=10, pady=10)
b = button(frame, text=”button”)
b.grid(column=0, row=0)
Create a variable in a radio button, define what type of variable it is and then retrieve it via a label
r = IntVar()
btn = Radiobutton(root, text=”one”, variable=r, value=1, command=clicked)
def clicked():
lbl = Label(root, text=r.get())
lbl.grid()
You have created the following list of tuples:
list = [
(“pepperoni”, “pepperoni”),
(“cheese”, “cheese”)
]
using a for loop, create 2 radio buttons that supply the name of the topping and supply a value of the topping to go into the “pizza” variable
for text, mode in list:
Radiobutton(root, text=text, variable=pizza, value=mode).pack
Create a yes or no button
If we put it into a variable what does it translate as?
How can you used this for your code?
from tkinter import messagebox
1 yes
2 no
We can put this in an if statement to do different things.
def clicked()
response = messagebox.askyesno(“Popup name”,”popup body”)
Label(root, text=response).pack()
if response == 1:
What are the different options for popups in Tkinter?
from tkinter import messagebox
messagabox.showinfo
messagabox.showwarning
messagabox.showerror
messagabox.askquestion
messagabox.askokcancel
messagabox.askyesno
These will all return 1, 0, or yes, ok, no, etc.
What command would you use if your wanted to create an additional second window
When you create a button to create a second window it will be created but your pictures won’t be. How do we fix this
How do we create a button to close this?
def open()
global top
global my_img
top = Toplevel()
top.title(“title”)
top.iconbitmap(‘c:/gui/codemy.ico’)
my_img = ImageTk.PhotoImage(Image.open(“images/aspen.png”)
my_label = Label(top, image=myi_img).pack()
btn2 = Button(top, text=”Close”, command=top.destroy).pack()
-in your function top.destroy()
make my_img a global variable
If you wanted to have tkinter open your file explorer, let you select a file “based on what you dictate you want” and to use that file what would you import and how would you use it?
What we’ll do is use fileddialog to let you pick a file, then we’ll print root.filename (this just shows the file path) next we’ll convert to an image (using root.filename as the path, then we’ll create a label for it and pack so it appears on the screen.
from tkinter import filedialog
def open():
global my_image
root.filename = filedialog.askopenfilename(initialdir=”/Users”, title=”Select a file”, filetypes=((“png files”, “.png”),(“all files”, “.*”)))
my_label = Label(root, text=root.filename).pack()
my_image = ImageTk.PhotoImage(Image.open(root.filename))
my_image_label = Label(image=my_image).pack()
btn = Button(root, text=”Select Image”, command=open).pack()
How would you create a slider (horizontal and vertical)?
hor = Scale(root, from_=0, to=400, orient=HORIZONTAL)
hor.pack()
ver = Scale(root, from_=0, to=400)
ver.pack()
Create a checkbox that sends it’s value to a variable
give the box a different value than the standard 0 or 1
If you change the value, the widget will not work properly, fix this issue
var = StringVar()
c = Checkbutton(root, text=”Check me out”, variable=var, onvalue=”on” offvalue=”off”)
c.deselect()
c.pack()
Create a list of days and put it in a list, put that list of days in a drop down menu.
Create a string variable named clicked, give that variable a default value of Monday. This variable will store what day you select
days = [
“monday”,
“tuesday”,
“Wednesday”,
“Thursday”,
“Friday”
]
clicked = StringVar()
clicked.set(“Monday”)
drop = OptionMenu(root, clicked, *days)
What are the four database types in SQLLite?
text
integer
reel - decimal
null - does or doesn’t exist
blob - images/videos
Create a SQLLite database and call it address_book.db
Next create the below columns that should be the text data type and the final one that should be an integer:
first_name
last_name
address
city
state
zipcode
Put these all in a table named “addresses”
import sqlite3
Create/open a db
conn = sqlite3.connect(‘‘address_book.db)
create a cursor, to send off and do stuff
c = conn.cursor()
c.execute(“"”CREATE TABLE addresses (
first_name text,
last_name text,
address text,
city text,
state text,
zip integer
)”””)
Commit changes
conn.commit()
Close connection
conn.close()
What does ipadx/ipady do?
spans it from the inside
Create a button for your address_book.db that allows you to insert data into it.
Let’s say we created f_name = Entry(root, width=30) already and we want to send this first name to our database.
Have this button delete the field in your entry afterword
Next create a query function
Now Delete a record
Now select an oid to use in a function
update a record
There’s also fetchmany(12), fetchnone, etc
def delete():
conn = sqlite3.connect(“admin.db”)
c = conn.cursor()
c.execute(“"”DELETE from addresses WHERE oid=””” + o.get())
conn.commit()
conn.close()
def query():
conn = sqlite3.connect(“admin.db”)
c = conn.cursor()
c.execute(“SELECT * FROM addresses”)
record = c.fetchall()
lbl = Label(root, text=record)
lbl.grid()
conn.commit()
conn.close()
def submit():
conn = sqlite3.connect(“admin.db”)
c = conn.cursor()
c.execute(“INSERT INTO addresses VALUES (?, ?)”,
(f.get(),
l.get())
)
conn.commit()
conn.close()
f.delete(0, END)
l.delete(0, END)
def update():
global update
conn = sqlite3.connect(“admin.db”)
c = conn.cursor()
c.execute(“UPDATE addresses SET f_name=?, l_name=?”, (f.get(), l.get()))
conn.commit() conn.close() f.delete(0, END) l.delete(0, END)
conn = sqlite3.connect(“admin.db”)
c = conn.cursor()
c.execute(“"”CREATE TABLE IF NOT EXISTS addresses(
f_name text,
l_name text
)
“””
)
conn.commit()
conn.close()
create a tab
What would you do if you only wanted space above, but not below using pady
\t
pady = (10, 0)
How do you make your gui unable to be resized
root.resizable(width=False, height=False)
Import what you would need to use an api
Use the api
import requests
import json
api_request = requests.get(“https://yourapi.org”)
api = json.loads(api_request.content)
if you print the api,