Tutorial do GUI tkinter do Python

Volta ao Menu Principal

Você poderá baixar (downloding) desta página em (download)

Radio Button Tkinter

import tkinter as tk
from tkinter import ttk
from tkinter.messagebox import showinfo

# root window (janela raiz)
root = tk.Tk()
root.geometry('300x220')
root.resizable(False, False)
root.title('Radio Button Demo')


def show_selected_size():
    showinfo(
        title='Resultado',
        message=selected_size.get()
    )


selected_size = tk.StringVar()
sizes = (('Pequeno', 'P'),
         ('Médio', 'M'),
         ('Grande', 'G'),
         ('Extra Grande', 'XG'),
         ('Extra Extra Grande', 'XXG'))

# label
label = ttk.Label(text="Qual é o seu temanho de t-shirt?")
label.pack(fill='x', padx=5, pady=5)

# radio buttons
for size in sizes:
    r = ttk.Radiobutton(
        root,
        text=size[0],
        value=size[1],
        variable=selected_size
    )
    r.pack(fill='x', padx=5, pady=5)

# button
button = ttk.Button(
    root,
    text="Pega o Tamanho Selecionado",
    command=show_selected_size)     #executa a função show_selected_size

button.pack(fill='x', padx=5, pady=5)


root.mainloop()

LabelFrame Tkinter

import tkinter as tk
from tkinter import ttk

# janela root
root = tk.Tk()

# configura a janela raiz (root)
root.geometry('300x200')
root.resizable(False, False)
root.title('LabelFrame Demo')


# label frame lf
lf = ttk.LabelFrame(root, text='Alinhamento')
lf.grid(column=0, row=0, padx=20, pady=20)

alignment_var = tk.StringVar()
alignments = ('Esquerda', 'Centro', 'Direita')

# cria radio buttons e os coloca na label frame

grid_column = 0
for alignment in alignments:
    # cria um radio button
    radio = ttk.Radiobutton(lf, text=alignment, value=alignment, variable=alignment_var)
    radio.grid(column=grid_column, row=0, ipadx=10, ipady=10)
    # grid column
    grid_column += 1

root.mainloop()

LabelFrame com mensagem

import tkinter as tk
from tkinter import ttk

# root window
root = tk.Tk()

# configura a janela raiz (root)
root.geometry('300x200')
root.resizable(False, False)
root.title('LabelFrame Demo')

def show_selected_alignment():
    showinfo(
        title='Resultado',
        message=selected_alignment.get()
    )


selected_alignment = tk.StringVar()
alignments = (('Esquerdo', 'E'),
          ('Centro', 'C'),
         ('Direito', 'D'))

# label frame lf
lf = ttk.LabelFrame(root, text='Alinhamento')
lf.grid(column=0, row=0, padx=20, pady=20)


alignments = ('Esquerda', 'Centro', 'Direito')  #Nomeia os radio buttons

# cria radio buttons e os coloca na label frame

grid_column = 0
for alignment in alignments:
    # cria um radio button
    radio = ttk.Radiobutton(lf, text=alignment, value=alignment[0], 
                            variable=selected_alignment)
    radio.grid(column=grid_column, row=0, ipadx=10, ipady=10)
    
    grid_column += 1

    
# button para clicar e obter a mensagem
button = ttk.Button(
    root,
    text="Pega o Alinhamento Selecionado",
    command=show_selected_alignment)     #executa a função show_selected_alignment

button.grid(row=3,column=0)
    
root.mainloop()

import tkinter as tk
from tkinter import ttk

# root window
root = tk.Tk()
root.title('LabelFrame Label Anchor')

# label frame
lf = ttk.LabelFrame(root, text='Label Anchor')
lf.grid(column=0, row=0, padx=20, pady=20, sticky=tk.NSEW)

anchor_var = tk.StringVar()
anchors = {
    'nw': {'row': 0, 'column': 1},
    'n': {'row': 0, 'column': 2},
    'ne': {'row': 0, 'column': 3},
    'en': {'row': 1, 'column': 4},
    'e': {'row': 2, 'column': 4},
    'es': {'row': 3, 'column': 4},
    'se': {'row': 4, 'column': 3},
    's': {'row': 4, 'column': 2},
    'sw': {'row': 4, 'column': 1},
    'ws': {'row': 3, 'column': 0},
    'w': {'row': 2, 'column': 0},
    'wn': {'row': 1, 'column': 0}
}


def change_label_anchor():
    lf['labelanchor'] = anchor_var.get()


# create radio buttons and place them on the label frame
for key, value in anchors.items():
    # create a radio button
    radio = ttk.Radiobutton(
        lf,
        text=key.upper(),
        value=key,
        command=change_label_anchor,
        variable=anchor_var
    ).grid(**value, padx=10, pady=10, sticky=tk.NSEW)

# set the radio button selected
anchor_var.set(lf['labelanchor'])

# show the root window
root.mainloop()

CHECKBOX Tkinter

import tkinter as tk
from tkinter import ttk
from tkinter.messagebox import showinfo

root = tk.Tk()
root.geometry('300x200')
root.resizable(False, False)
root.title('Checkbox Demo')

agreement = tk.StringVar()


def agreement_changed():
    tk.messagebox.showinfo(title='Resultado',
                        message=agreement.get())


ttk.Checkbutton(root,
                text='Eu concordo',
                command=agreement_changed,
                variable=agreement,
                onvalue='concordo',
                offvalue='discordo').pack()


root.mainloop()

Mais CHECKBOX...

from tkinter import ttk
from tkinter.messagebox import showinfo

root = tk.Tk()
root.geometry('300x200')
root.resizable(False, False)
root.title('Checkbox Demo')

acordo = tk.StringVar()


def acordo_mudado():
    tk.messagebox.showinfo(title='Resultado',
                        message=acordo.get())


ttk.Checkbutton(root,
                text='Eu concordo',
                command=acordo_mudado,
                variable=acordo,
                onvalue='concordo',
                offvalue='discordo').pack()


root.mainloop()

COMBOBOX

import tkinter as tk
from tkinter import ttk
from tkinter.messagebox import showinfo
from calendar import month_name

root = tk.Tk()

# config a janela root
root.geometry('300x200')
root.resizable(False, False)
root.title('Widget Combobox')

# label
label = ttk.Label(text="Por gentileza, selecione um mês:")
label.pack(fill=tk.X, padx=5, pady=5)

# create a combobox
selected_month = tk.StringVar()
month_cb = ttk.Combobox(root, textvariable=selected_month)

# pega as 3 primeiras letras de cada nome do mês
month_cb['values'] = [month_name[m][0:3] for m in range(1, 13)]

# evita digitar um valor
month_cb['state'] = 'readonly'

# posiciona a widget
month_cb.pack(fill=tk.X, padx=5, pady=5)


# vincula as mudanças dos valores selecionados
def month_changed(event):
    """ manipula o evento mudança de mês """
    showinfo(
        title='Resultado',
        message=f'Você selecionou {selected_month.get()}!'
    )

month_cb.bind('<>', month_changed)

root.mainloop()

COMBOBOX com o método set()

import tkinter as tk
from tkinter import ttk
from tkinter.messagebox import showinfo
from calendar import month_name
from datetime import datetime

root = tk.Tk()

# config the root window
root.geometry('300x200')
root.resizable(False, False)
root.title('Combobox Widget')

# label
label = ttk.Label(text="Por gentileza, selecione um mês:")
label.pack(fill=tk.X, padx=5, pady=5)

# cria uma combobox
selected_month = tk.StringVar()
month_cb = ttk.Combobox(root, textvariable=selected_month)

# pega as 3 primeiras letras do nome de cada mês
month_cb['values'] = [month_name[m][0:3] for m in range(1, 13)]

# prevent typing a value
month_cb['state'] = 'readonly'

# place the widget
month_cb.pack(fill=tk.X, padx=5, pady=5)


# vincula as mudanças do selected value
def month_changed(event):
    """ manipula o evento month changed """
    showinfo(
        title='Result',
        message=f'Você selecionou {selected_month.get()}!'
    )


month_cb.bind('<>', month_changed)

# configura o mês corrente
current_month = datetime.now().strftime('%b')
month_cb.set(current_month)

root.mainloop()