Tkinter

From Network Security Wiki
Jump to navigation Jump to search


Basics

  • Installing
sudo apt install python-tk
sudo apt install python3-tk
  • Importing
try:
    from Tkinter import *     # for Python2
except ImportError:
    from tkinter import *     # for Python3
  • Importing as per PEP8:
import tkinter as tk
root = tk.Tk()
tk.Button(...)

Bit more typing but similar:

import tkinter
root = tkinter.Tk()
tkinter.Button(...)

Hello World Example

from tkinter import Tk, Label

root = Tk()

header = Label(root, text="Renamer App v1.0")
header.pack()

root.mainloop()

Frame

import tkinter as tk

root = tk.Tk()

#Frame 1
frame1 = tk.Frame(root, height=300, width=200, background="red")
frame1.grid(row=0, column=0)

# Frame 2
tk.Frame(root, height=300, width=200, background="yellow").grid(row=0, column=1)

root.mainloop()

Buttons

from tkinter import Tk, Button

root = Tk()

def backup():
    print("Backup Files")

a = Button(root, text="Backup Files", command=backup)
a.pack()

root.mainloop()

Label

from Tkinter import *
master = Tk()

w = Label(master, text="Hello, world!")
w.pack()

mainloop()

Listbox

  • Defining Listbox:
listbox = Listbox(root, height=30, width=100)
listbox.xview_scroll(3, "pages")
listbox.yview_scroll(3, "pages")
listbox.grid(row=7, columnspan=3)
  • Inserting output:
listbox.insert(END, "1st Entry")
  • Deleting Output:
listbox.delete(0, END)
  • Auto-scrolling Scrollbar:
from tkinter import *

root = Tk()

scrollbar = Scrollbar(root, orient=VERTICAL)
listbox = Listbox(root, height=10, width=70, yscrollcommand=scrollbar.set)
listbox.xview_scroll(3, "pages")
listbox.yview_scroll(3, "pages")
scrollbar.config(command=listbox.yview)
listbox.grid(row=0, column=0, rowspan=10, columnspan=10)
scrollbar.grid(row=0, column=11, rowspan=10, columnspan=1, sticky=W, ipady = 60)

for i in range(40):
    listbox.insert(END, "This is Test Line no: "+str(i))

root.mainloop()

Input

root = Tk()

en = Entry(root, width=60)
en.pack()
en.focus_set()

mainloop()

Output in CLI

from tkinter import *
master = Tk()

def callback():
    print ("My Message")

Button(master, text="get", width=10, command=callback).pack()

mainloop()

Output in GUI

from tkinter import *
master = Tk()

def callback():
    Label(master, text="Callback Function").pack()

Button(master, text="get", width=10, command=callback).pack()
mainloop()

Pack Manager

from Tkinter import *
root = Tk()

w = Label(root, text="Red", bg="red", fg="white")
w.pack()

Label(root, text="Green", bg="green", fg="black").pack()

mainloop()

Grid Manager

from tkinter import *

root = Tk()

Button(root, text="files", width=20, command="ls").grid(row=0, column=0)
Button(root, text="Clear", width=20, command="clear").grid(row=0, column=1)
Button(root, text="Backup", width=20, command="backup").grid(row=1, column=0)
Button(root, text="Miss", width=20, command="miss").grid(row=1, column=1)

root.mainloop()

Filedialog

import tkinter
from tkinter import filedialog
import os

root = tkinter.Tk()
root.withdraw() #use to hide tkinter window

currdir = os.getcwd()
dir = filedialog.askdirectory(parent=root, initialdir=currdir, title='Please select a directory')
if len(dir) > 0:
    print ("You chose %s" % dir)

Toplevel

Method to create Child Windows:

from tkinter import Button, Toplevel, Tk

root = Tk()

def press():
    win1 = Toplevel()
    win1.attributes('-topmost', 'true')
    Button(win1, text = "Event", command=event).grid()
    Button(win1, text = "Q", command=win1.destroy).grid()

def event():
    print("Event Printed")

Button(root, text = "A", command=press).grid()
root.geometry('200x200')
root.mainloop()

Key Bindings

from tkinter import *
 def hello(event):
    print("A Clicked, Button-l") 
def quit(event):                           
    print("Q Clicked, so let's stop") 

widget.bind('a', hello)
widget.bind('q', quit)

Progress Bar

from tkinter.ttk import Progressbar

bar = Progressbar(root, length=400)
bar.grid(row=15, column=1, rowspan=1, columnspan=9)     # Progress Bar

bar['value'] = 70

Cursors

  • Over Buttons:
from tkinter import *
import tkinter

top = Tk()

B1 = Button(top, text = "circle", relief = RAISED, cursor = "circle")
B2 = Button(top, text = "plus", relief = RAISED, cursor = "plus")
B1.pack()
B2.pack()
top.mainloop()
  • For Root Window when busy:
def long_func():
    root.config(cursor="watch")
    root.update()
    time.sleep(30)
    root.config(cursor="")

MessageBox

To show a message box using Tkinter, you can use messagebox library like this:

  • Showinfo:
 from tkinter import messagebox
 messagebox.showinfo('Message title','Message content', parent=frame)
  • Warn or Error:
 messagebox.showwarning('Message title', 'Message content', parent=frame)  #shows warning message
 messagebox.showerror('Message title', 'Message content', parent=frame)    #shows error message
  • Askquestion dialogs:
res = messagebox.askquestion('Message title','Message content', parent=frame)
res = messagebox.askyesno('Message title','Message content', parent=frame)
res = messagebox.askyesnocancel('Message title','Message content', parent=frame)
res = messagebox.askokcancel('Message title','Message content', parent=frame)
res = messagebox.askretrycancel('Message title','Message content', parent=frame)
  • Example for a message box when the user clicks a button:
from tkinter import *
from tkinter import messagebox

root = Tk()

def clicked():
    messagebox.showinfo('Message title', 'Message content', parent=root)

btn = Button(root,text='Click here', command=clicked)
btn.grid(column=0,row=0)

window.title("Another Test App")
window.geometry('350x200')
window.mainloop()

SpinBox

  • To create a Spinbox widget, you can use Spinbox class like this:
spin = Spinbox(window, from_=0, to=100)
spin = Spinbox(window, from_=0, to=100, width=5)
  • Complete example:
from tkinter import *
window = Tk()
window.title("This is a Test App")
window.geometry('350x200')
spin = Spinbox(window, from_=0, to=100, width=5)
spin.grid(column=0,row=0)
window.mainloop()

Menu Bar

To add a menu bar, you can use menu class like this:

from tkinter import *
from tkinter import Menu

window = Tk()
window.title("This is Test App")

def clicked():
    print("Clicked Selected")

menu = Menu(window)
new_item = Menu(menu, tearoff=0)
new_item.add_command(label='Click', command=clicked)
new_item.add_separator()
new_item.add_command(label='Exit', command=exit)
menu.add_cascade(label='File', menu=new_item)

window.config(menu=menu)
window.mainloop()

Notebook widget (tab control)

To create a tab control follow these steps:

  1. Create a tab control using Notebook class
  2. Create a tab using Frame class.
  3. Add that tab to the tab control.
  4. Pack the tab control so it becomes visible in the window.
from tkinter import *
from tkinter import ttk

window = Tk()
window.title("This is a test App")
tab_control = ttk.Notebook(window)
tab1 = ttk.Frame(tab_control)
tab_control.add(tab1, text='First')
tab_control.pack(expand=1, fill='both')

window.mainloop()

Add widgets to Notebooks

After creating tabs, you can put widgets inside these tabs by assigning the parent property to the desired tab.

from tkinter import *
from tkinter import ttk

window = Tk()
window.title("Welcome to Test app")

tab_control = ttk.Notebook(window)
tab1 = ttk.Frame(tab_control)
tab2 = ttk.Frame(tab_control)
tab_control.add(tab1, text='First')
tab_control.add(tab2, text='Second')

lbl1 = Label(tab1, text= 'label1')
lbl1.grid(column=0, row=0)
lbl2 = Label(tab2, text= 'label2')
lbl2.grid(column=0, row=0)

tab_control.pack(expand=1, fill='both')
window.mainloop()

Display window in Center

import tkinter

def center(toplevel):
    toplevel.update_idletasks()
    w = toplevel.winfo_screenwidth()
    h = toplevel.winfo_screenheight()
    size = tuple(int(_) for _ in toplevel.geometry().split('+')[0].split('x'))
    x = w/2 - size[0]/2
    y = h/2 - size[1]/2
    toplevel.geometry("%dx%d+%d+%d" % (size + (x, y)))

root = Tk()

win = Toplevel(root)
win.title("Centered!")
center(win)

root.mainloop()


References





blog comments powered by Disqus