Developer Snippet Diary

TKinter create GUI in python

Tkinter − Main Tkinter module and few others:
tkinter.colorchooser, tkinter.commondialog , tkinter.filedialog, tkinter.font, tkinter.messagebox, tkinter.scrolledtext, tkinter.simpledialog, tkinter.ttk

How to create: 

import tkinter as tk                          #step 1 to import

window = tk.Tk()                             #step 2 Create the main window
                                                        ############ step 3 add widgets here
w = tk.Button ( window, text ="Hello" ) 
w.place(x=50,y=50)

window.mainloop()                         # 4. Start the main event loop

OOP BASED CODE: IF COMPLEX CODE USE LIKE BELOW

import tkinter as tk
class App(tk.Tk):
   def __init__(self):
      super().__init__()

app = App()
app.mainloop()

PLACEMENT: placed elements on main window
.pack(), .place(), .grid()

WIDGETS:
1. Button
w = Button ( master, option=value, ... )

activebackground ,bg, activeforeground, fg   = color name || change backgrounds and text colors
bd: border width in pixels ie bd="6"
font = to set font
height:Height of the button in text lines
image: display image in place of text
justify: CENTER, LEFT, RIGHT
padx, pady : paddings on x axis and y axis
state: disabled,normal
underline = 1|-1 (-1 means not underline)
width = pixels
wraplength = pixels #wrap text

command = A procedure to be called every time the user changes the state of this element

window = tk.Tk()
w = tk.Button ( window, text ="Hello", activeforeground ="red",bd="6", height="3" ,state="disabled",width="33",wraplength="1")
w.place(x=50,y=50)

2. check button w = Checkbutton ( master, option, ... )

Onvalue : when checked the value default 1
Offvalue: when unched the value default 0
variable = IntVar() : tracks the current state of the checkbutton : from tkinter import Tk, IntVar  OR from tkinter import *

CheckVar1 = IntVar()
C1 = Checkbutton(window, text = "Music", variable = CheckVar1, onvalue = 1, offvalue = 0, height=5, width = 20)
C1.pack()

3. Entry w = Entry( master, option, ... )
show="* || ANY Charter" : by default text
get() Returns the entry's current text as a string.
select_clear() Clears the selection.

E1 = Entry(window, bd =5, show="x")
E1.pack(side = RIGHT)

4. Label w = Label ( master, option, ... )

var = StringVar()
label = Label( window, textvariable=va )
var.set("Hey!? How are you doing?")
label.pack()

5.Listbox  w = Listbox ( master, option, ... )
display a list of items from which a user can select a number of items.

selectmode:  browse(def), SINGLE, MULTIPLE, EXTENDED (from 1 to nth)
Xscrollcommand, Yscrollcommand: scroll the listbox horizontally | vertically
activate ( index ) : default selection
insert ( index, *elements ) : insert new element

Lb1 = Listbox(window, selectmode="extended")
Lb1.insert(1, "Python")
Lb1.insert(2, "Perl")
Lb1.insert(3, "C")
Lb1.pack()


6. Menu w = Menu ( master, option, ... )

Postcommand: You can set this option to a procedure, and that procedure will be called every time someone brings up this menu.
Tearoff: tearoff=1 → enables menu to be torn off into a new window. tearoff=0 → disables this behavior

add_command (options) : Adds a menu item to the menu.
add_radiobutton( options ) Creates a radio button menu item.
add( type, options ) Adds a specific type of menu item to the menu.
add_separator() Adds a separator line to the menu.
add_cascade(options) Creates a new hierarchical menu by associating a given menu to a parent menu.

from tkinter import *
import tkinter as tk

def donothing():
   filewin = Toplevel(window)
   button = Button(filewin, text="Do nothing button")
   button.pack()

# Create the main window
window = tk.Tk()

menubar = Menu(window)
filemenu = Menu(menubar, tearoff=0)
filemenu.add_command(label="New", command=donothing)
filemenu.add_command(label="Open", command=donothing)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=window.quit)
menubar.add_cascade(label="File", menu=filemenu)

editmenu = Menu(menubar, tearoff=0)
editmenu.add_command(label="Undo", command=donothing)
editmenu.add_separator()
editmenu.add_command(label="Cut", command=donothing)
menubar.add_cascade(label="Edit", menu=editmenu)

helpmenu = Menu(menubar, tearoff=0)
helpmenu.add_command(label="Help Index", command=donothing)
helpmenu.add_command(label="About...", command=donothing)
menubar.add_cascade(label="Help", menu=helpmenu)

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

7. Drop down button:  w = Menubutton ( master, option, ... )

# Create the main window
window = tk.Tk()
mb= Menubutton ( window, text="condiments" )
mb.grid()
mb.menu = Menu ( mb, tearoff = 0 )
mb["menu"] = mb.menu

mayoVar = IntVar()
ketchVar = IntVar()
mb.menu.add_checkbutton (label="mayo", variable=mayoVar)
mb.menu.add_checkbutton (label="ketchup", variable=ketchVar)
mb.pack()

8. Radio Button : w = Radiobutton ( master, option, ... )

window = tk.Tk()

def sel():
   selection = "You selected the option " + str(var.get())
   label.config(text = selection)

var = IntVar()
R1 = Radiobutton(window, text="Option 1", variable=var, value=1, command=sel)
R1.pack()
R2 = Radiobutton(window, text="Option 2", variable=var, value=2, command=sel)
R2.pack()
R3 = Radiobutton(window, text="Option 3", variable=var, value=3, command=sel)
R3.pack()
label = Label(window)
label.pack()

9. Message: w = Message ( master, option, ... )

This widget provides a multiline and noneditable object that displays texts, automatically breaking lines and justifying their contents.

var = StringVar()
message = Message(window, textvariable=var)
var.set("Hey!? How are you doing?")
message.pack()

10. TEXT : w = Text ( master, option, ... )
Text widgets provide advanced capabilities that allow you to edit a multiline text and format the way it has to be displayed, such as changing its color and font.

text = Text(window)
text.insert(INSERT, "Hello.....")
text.insert(END, "Bye Bye.....")
text.pack()

11. Scrollbar w = Scrollbar ( master, option, ... )

scrollbar = Scrollbar(window)
scrollbar.pack( side = RIGHT, fill=Y )

mylist = Listbox(window, yscrollcommand = scrollbar.set )
for line in range(100):
   mylist.insert(END, "This is line number " + str(line))
  
mylist.pack( side = LEFT, fill = BOTH )
scrollbar.config( command = mylist.yview )

 

 

FOR MORE VISIT:
https://www.tutorialspoint.com/python/python_gui_programming.htm

Posted by: R GONDAL
Email: rizikmw@gmail.com