01. Primi passi

Hello World!

Esempio:

  • Codice sorgente

from tkinter import *

window = Tk()

window.title("Hello World!")

window.mainloop()

Widget

Esempio:

  • Codice sorgente

from tkinter import *

window = Tk()

window.title("Hello World!")

window.geometry('400x300')

lbl1 = Label(window, text="Label1")

lbl1.grid(column=0, row=0)

lbl2 = Label(window, text="Label2")

lbl2.grid(column=0, row=1)

lbl2.grid(sticky=E)

lbl3 = Label(window, text="Label3")

lbl3.grid(column=0, row=2)

lbl3.grid(sticky=W)

lbl4 = Label(window, text="Label4")

lbl4.grid(column=0, row=3)

lbl4.grid(sticky=N+S+E+W)

lbl4 = Label(window, text="Label5", font=("Times", 16, "bold italic"),

bg="orange", fg="red")

lbl4.grid(column=0, row=4)

btn = Button(window, text="Clicca qui", font=("Arial", 12, "bold"),

bg="green",)

btn.grid(column=2, row=0)

txt = Entry(window, width=10)

txt.grid(column=2, row=2)

txt.grid(sticky=E)

window.mainloop()

Gestione degli eventi

Esempio:

  • Codice sorgente

from tkinter import *

def click_conferma():

global n_conferme

n_conferme += 1

lbl1.configure(text="Numero di conferme: "+str(n_conferme))

lbl2.configure(text="Ultima lettura: "+txt.get())

def click_abilita():

txt.config(state="normal")

btn1.config(state="normal")

def click_disabilita():

txt.config(state="disabled")

btn1.config(state="disabled")

n_conferme = 0

window = Tk()

window.title("Gestione eventi")

window.geometry('400x300')

window.rowconfigure(0, weight=0)

window.rowconfigure(1, weight=0)

window.rowconfigure(2, weight=0)

window.rowconfigure(3, weight=1)

window.rowconfigure(4, weight=0)

window.rowconfigure(5, weight=2)

lbl1 = Label(window, text="Numero di conferme: 0")

lbl1.grid(column=0, row=0)

lbl1.grid(sticky=W)

lbl2 = Label(window, text="*******")

lbl2.grid(column=0, row=1)

lbl2.grid(sticky=W)

txt = Entry(window, width=20)

txt.grid(column=0, row=2)

txt.grid(sticky=W)

btn1 = Button(window, text="Conferma", command=click_conferma)

btn1.grid(column=1, row=2)

btn2 = Button(window, text="Abilita", command=click_abilita)

btn2.grid(column=0, row=4, ipadx=15, ipady=15)

btn3 = Button(window, text="Disabilita", command=click_disabilita)

btn3.grid(column=1, row=4, ipadx=15, ipady=15)

window.mainloop()