Centering a window
# utility function that centers the program window on our screen
def center_window(toplevel):
toplevel.update_idletasks()
screen_width = toplevel.winfo_screenwidth()
screen_height = toplevel.winfo_screenheight()
size = tuple(int(_) for _ in toplevel.geometry().split('+')[0].split('x'))
x = screen_width/2 - size[0]/2
y = screen_height/2 - size[1]/2
toplevel.geometry("+%d+%d" % (x, y))
Customized title bar
def move_window(event):
window.geometry('+{0}+{1}'.format(event.x_root, event.y_root))
window=tk.Tk()
window.title("Cutom title bar")
window.iconbitmap(default='icon.ico')
window.config(borderwidth=2)
window.columnconfigure(0,minsize=600)
window.rowconfigure([0],minsize=30)
window.rowconfigure([1,2],minsize=100)
# hiding the default title bar
window.overrideredirect(True)
topbar_frame=tk.Frame(master=window,bg="#f20011",bd=2)
lbl_title=tk.Label(master=topbar_frame,text="Shopify Order", background=TOP_BACKGROUND_COLOR,foreground="#fafafa")
lbl_title.pack(side=tk.LEFT)
# put a close button on the title bar
close_button = tk.Button(topbar_frame, text=' X ',borderwidth=0,relief=tk.SOLID,background="#ff3d57",activebackground="#e3001e",foreground="#ebebeb",command=window.destroy)
close_button.pack(side=tk.RIGHT)
min_button = tk.Button(topbar_frame, text=' _ ',borderwidth=0,relief=tk.SOLID,background="#ededeb",activebackground="#e3001e",foreground="#000000",command=lambda:window.wm_state("iconic"))
min_button.pack(side=tk.RIGHT)
# bind title bar motion to the move window function
topbar_frame.bind('<B1-Motion>', move_window)
topbar_frame.grid(row=0,column=0,sticky='new')
window.mainloop()
Showing progressbar while downloading a file
import tkinter as tk
import tkinter.ttk as ttk
import requests
import threading
import tempfile
import os
import time
progress_window=tk.Tk()
progress_window.geometry('400x60')
progress_window.title("Querying file size..")
progressbar=ttk.Progressbar(master=progress_window, orient = tk.HORIZONTAL,
length = 100, mode = 'determinate')
progressbar.pack(ipadx=4,ipady=4,padx=(12,12),pady=(12,12))
def download_file():
session=requests.Session()
response=session.get("http://ipv4.download.thinkbroadband.com/10MB.zip",stream=True)
total_size_in_bytes= int(response.headers.get('Content-Length', 500*1024))
block_size = 1024*50 # 50kb block size
with tempfile.TemporaryDirectory() as tmp_dir:
tmp_filename=os.path.join(tmp_dir,'response.data')
with open(tmp_filename, 'wb') as file:
downloaded=0
for data in response.iter_content(block_size):
file.write(data)
downloaded+=len(data)
if downloaded==0:
progressbar['value']=0
else:
progressbar['value'] = int((downloaded/total_size_in_bytes)*100)
progress_window.title(f"Downloaded {downloaded} of {total_size_in_bytes} bytes.")
progress_window.update()
time.sleep(.1)
progress_window.destroy()
progress_window.after(300,lambda: threading.Thread(target=download_file).start())
progress_window.mainloop()