2022年11月29日 星期二

Tkinter Gui With Sqlite

 

Tkinter Gui With Sqlite

https://www.python4networkengineers.com/posts/python-intermediate/create_a_tkinter_gui_with_sqlite_backend/




(1)


from tkinter import *

from tkinter.ttk import Treeview

app = Tk()

frame_search = Frame(app)

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


lbl_search = Label(frame_search, text='Search by hostname',

                   font=('bold', 12), pady=20)

lbl_search.grid(row=0, column=0, sticky=W)

hostname_search = StringVar()

hostname_search_entry = Entry(frame_search, textvariable=hostname_search)

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


lbl_search = Label(frame_search, text='Search by Query',

                   font=('bold', 12), pady=20)

lbl_search.grid(row=1, column=0, sticky=W)

query_search = StringVar()

query_search.set("Select * from routers where ram>1024")

query_search_entry = Entry(frame_search, textvariable=query_search, width=40)

query_search_entry.grid(row=1, column=1)


(2)


from tkinter import *

from tkinter.ttk import Treeview

#-----------------------------------------------------------------------------------------

app = Tk()

frame_search = Frame(app)

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


lbl_search = Label(frame_search, text='Search by hostname',

                   font=('bold', 12), pady=20)

lbl_search.grid(row=0, column=0, sticky=W)

hostname_search = StringVar()

hostname_search_entry = Entry(frame_search, textvariable=hostname_search)

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


lbl_search = Label(frame_search, text='Search by Query',

                   font=('bold', 12), pady=20)

lbl_search.grid(row=1, column=0, sticky=W)

query_search = StringVar()

query_search.set("Select * from routers where ram>1024")

query_search_entry = Entry(frame_search, textvariable=query_search, width=40)

query_search_entry.grid(row=1, column=1)


#-----------------------------------------------------------------------------------------

frame_fields = Frame(app)

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

# hostname

hostname_text = StringVar()

hostname_label = Label(frame_fields, text='hostname', font=('bold', 12))

hostname_label.grid(row=0, column=0, sticky=E)

hostname_entry = Entry(frame_fields, textvariable=hostname_text)

hostname_entry.grid(row=0, column=1, sticky=W)

# BRAND

brand_text = StringVar()

brand_label = Label(frame_fields, text='Brand', font=('bold', 12))

brand_label.grid(row=0, column=2, sticky=E)

brand_entry = Entry(frame_fields, textvariable=brand_text)

brand_entry.grid(row=0, column=3, sticky=W)

# RAM

ram_text = StringVar()

ram_label = Label(frame_fields, text='RAM', font=('bold', 12))

ram_label.grid(row=1, column=0, sticky=E)

ram_entry = Entry(frame_fields, textvariable=ram_text)

ram_entry.grid(row=1, column=1, sticky=W)

# FLASH

flash_text = StringVar()

flash_label = Label(frame_fields, text='Flash', font=('bold', 12), pady=20)

flash_label.grid(row=1, column=2, sticky=E)

flash_entry = Entry(frame_fields, textvariable=flash_text)

flash_entry.grid(row=1, column=3, sticky=W)


(3)





from tkinter import *

from tkinter.ttk import Treeview

from db import Database


#-----------------------------------------------------------------------------------------


def populate_list(hostname=''):

    for i in router_tree_view.get_children():

        router_tree_view.delete(i)

    for row in db.fetch(hostname):

        router_tree_view.insert('', 'end', values=row)


def populate_list2(query='select * from routers'):

    for i in router_tree_view.get_children():

        router_tree_view.delete(i)

    for row in db.fetch2(query):

        router_tree_view.insert('', 'end', values=row)


def add_router():

    if brand_text.get() == '' or hostname_text.get() == '' or ram_text.get() == '' or flash_text.get() == '':

        messagebox.showerror('Required Fields', 'Please include all fields')

        return

    db.insert(hostname_text.get(), brand_text.get(),

              ram_text.get(), flash_text.get())

    clear_text()

    populate_list()



def select_router(event):

    try:

        global selected_item

        index = router_tree_view.selection()[0]

        selected_item = router_tree_view.item(index)['values']

        hostname_entry.delete(0, END)

        hostname_entry.insert(END, selected_item[1])

        brand_entry.delete(0, END)

        brand_entry.insert(END, selected_item[2])

        ram_entry.delete(0, END)

        ram_entry.insert(END, selected_item[3])

        flash_entry.delete(0, END)

        flash_entry.insert(END, selected_item[4])

    except IndexError:

        pass


def remove_router():

    remove(selected_item[0])

    clear_text()

    populate_list()


def update_router():

    db.update(selected_item[0], hostname_text.get(), brand_text.get(),

              ram_text.get(), flash_text.get())

    populate_list()


def clear_text():

    brand_entry.delete(0, END)

    hostname_entry.delete(0, END)

    ram_entry.delete(0, END)

    flash_entry.delete(0, END)


def search_hostname():

    hostname = hostname_search.get()

    populate_list(hostname)



def execute_query():

    query = query_search.get()

    populate_list2(query)


#-----------------------------------------------------------------------------------------

app = Tk()

frame_search = Frame(app)

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


lbl_search = Label(frame_search, text='Search by hostname',

                   font=('bold', 12), pady=20)

lbl_search.grid(row=0, column=0, sticky=W)

hostname_search = StringVar()

hostname_search_entry = Entry(frame_search, textvariable=hostname_search)

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


lbl_search = Label(frame_search, text='Search by Query',

                   font=('bold', 12), pady=20)

lbl_search.grid(row=1, column=0, sticky=W)

query_search = StringVar()

query_search.set("Select * from routers where ram>1024")

query_search_entry = Entry(frame_search, textvariable=query_search, width=40)

query_search_entry.grid(row=1, column=1)


#-----------------------------------------------------------------------------------------

frame_fields = Frame(app)

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

# hostname

hostname_text = StringVar()

hostname_label = Label(frame_fields, text='hostname', font=('bold', 12))

hostname_label.grid(row=0, column=0, sticky=E)

hostname_entry = Entry(frame_fields, textvariable=hostname_text)

hostname_entry.grid(row=0, column=1, sticky=W)

# BRAND

brand_text = StringVar()

brand_label = Label(frame_fields, text='Brand', font=('bold', 12))

brand_label.grid(row=0, column=2, sticky=E)

brand_entry = Entry(frame_fields, textvariable=brand_text)

brand_entry.grid(row=0, column=3, sticky=W)

# RAM

ram_text = StringVar()

ram_label = Label(frame_fields, text='RAM', font=('bold', 12))

ram_label.grid(row=1, column=0, sticky=E)

ram_entry = Entry(frame_fields, textvariable=ram_text)

ram_entry.grid(row=1, column=1, sticky=W)

# FLASH

flash_text = StringVar()

flash_label = Label(frame_fields, text='Flash', font=('bold', 12), pady=20)

flash_label.grid(row=1, column=2, sticky=E)

flash_entry = Entry(frame_fields, textvariable=flash_text)

flash_entry.grid(row=1, column=3, sticky=W)


#-----------------------------------------------------------------------------------------

frame_router = Frame(app)

frame_router.grid(row=4, column=0, columnspan=4, rowspan=6, pady=20, padx=20)


columns = ['id', 'Hostname', 'Brand', 'Ram', 'Flash']

router_tree_view = Treeview(frame_router, columns=columns, show="headings")

router_tree_view.column("id", width=30)

for col in columns[1:]:

    router_tree_view.column(col, width=120)

    router_tree_view.heading(col, text=col)

router_tree_view.bind('<<TreeviewSelect>>', select_router)

router_tree_view.pack(side="left", fill="y")

scrollbar = Scrollbar(frame_router, orient='vertical')

scrollbar.configure(command=router_tree_view.yview)

scrollbar.pack(side="right", fill="y")

router_tree_view.config(yscrollcommand=scrollbar.set)


#-----------------------------------------------------------------------------------------

frame_btns = Frame(app)

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


add_btn = Button(frame_btns, text='Add Router', width=12, command=add_router)

add_btn.grid(row=0, column=0, pady=20)


remove_btn = Button(frame_btns, text='Remove Router',

                    width=12, command=remove_router)

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


update_btn = Button(frame_btns, text='Update Router',

                    width=12, command=update_router)

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


clear_btn = Button(frame_btns, text='Clear Input',

                   width=12, command=clear_text)

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


search_btn = Button(frame_search, text='Search',

                    width=12, command=search_hostname)

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


search_query_btn = Button(frame_search, text='Search Query',

                          width=12, command=execute_query)

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


#-----------------------------------------------------------------------------------------

app.title('Router Manager')

app.geometry('700x550')


db = Database("mydb.db")

# Populate data

populate_list("mydb.db")


# Start program

app.mainloop()


#-----------------------------------------------------------------------------------------
db.py
#-----------------------------------------------------------------------------------------

import sqlite3


class Database:

    def __init__(self, db):

        self.conn = sqlite3.connect(db)

        self.cur = self.conn.cursor()

        self.cur.execute(

            "CREATE TABLE IF NOT EXISTS routers (id INTEGER PRIMARY KEY, hostname text, brand text, ram integer, flash integer)")

        self.conn.commit()


    def fetch(self, hostname=''):

        self.cur.execute(

            "SELECT * FROM routers WHERE hostname LIKE ?", ('%'+hostname+'%',))

        rows = self.cur.fetchall()

        return rows


    def fetch2(self, query):

        self.cur.execute(query)

        rows = self.cur.fetchall()

        return rows


    def insert(self, hostname, brand, ram, flash):

        self.cur.execute("INSERT INTO routers VALUES (NULL, ?, ?, ?, ?)",

                         (hostname, brand, ram, flash))

        self.conn.commit()


    def remove(self, id):

        self.cur.execute("DELETE FROM routers WHERE id=?", (id,))

        self.conn.commit()


    def update(self, id, hostname, brand, ram, flash):

        self.cur.execute("UPDATE routers SET hostname = ?, brand = ?, ram = ?, flash = ? WHERE id = ?",

                         (hostname, brand, ram, flash, id))

        self.conn.commit()


    def __del__(self):

        self.conn.close()


Python tkinter+sqlite 學生資料管理系统

 Python tkinter+sqlite 學生資料管理系統




from tkinter import *

from tkinter.messagebox import *

import sqlite3

from tkinter import ttk


dbstr = "mydb.db"


root = Tk()

root.geometry('700x600')

root.title('學生資料管理系統')


Label(root, text="學號:").place(relx=0, rely=0.05, relwidth=0.1)

Label(root, text="姓名:").place(relx=0.5, rely=0.05, relwidth=0.1)

Label(root, text="電話:").place(relx=0, rely=0.1, relwidth=0.1)

Label(root, text="地址:").place(relx=0.5, rely=0.1, relwidth=0.1)


sid = StringVar()

name = StringVar()

phone = StringVar()

address = StringVar()

Entry(root, textvariable=sid).place(relx=0.1, rely=0.05, relwidth=0.37, height=25)

Entry(root, textvariable=name).place(relx=0.6, rely=0.05, relwidth=0.37, height=25)


Entry(root, textvariable=phone).place(relx=0.1, rely=0.1, relwidth=0.37, height=25)

Entry(root, textvariable=address).place(relx=0.6, rely=0.1, relwidth=0.37, height=25)


Label(root, text='學生資料管理', bg='white', fg='red', font=('宋体', 15)).pack(side=TOP, fill='x')


def createTable():

    # Create Table

    conn = sqlite3.connect('mydb.db')

    cursor = conn.cursor()

    '''

    ist1.append(sid.get())

    list1.append(name.get())

    list1.append(phone.get())

    list1.append(address.get())

    '''

    table_create_query = '''CREATE TABLE IF NOT EXISTS student 

                    (sid INTEGER PRIMARY KEY, name TEXT, phone TEXT, addressTEXT)

            '''

    conn.execute(table_create_query)

    conn.commit()

    conn.close()

    

def showAllInfo():

    x = dataTreeview.get_children()

    for item in x:

        dataTreeview.delete(item)

    con = sqlite3.connect(dbstr)

    cur = con.cursor()

    cur.execute("select * from student")

    lst = cur.fetchall()

    for item in lst:

        dataTreeview.insert("", 1, text="line1", values=item)

    cur.close()

    con.close()



def appendInfo():

    if sid.get() == "":

        showerror(title='提示', message='輸入不能為空白')

    elif name.get() == "":

        showerror(title='提示', message='輸入不能為空白')

    elif phone.get() == "":

        showerror(title='提示', message='輸入不能為空白')

    elif address.get() == "":

        showerror(title='提示', message='輸入不能為空白')

    else:

        x = dataTreeview.get_children()

        for item in x:

            dataTreeview.delete(item)

        list1 = []

        list1.append(sid.get())

        list1.append(name.get())

        list1.append(phone.get())

        list1.append(address.get())

        con = sqlite3.connect(dbstr)

        cur = con.cursor()

        cur.execute("insert into student values(?,?,?,?)", tuple(list1))

        con.commit()

        cur.execute("select * from student")

        lst = cur.fetchall()

        for item in lst:

            dataTreeview.insert("", 1, text="line1", values=item)

        cur.close()

        con.close()



def deleteInfo():

    con = sqlite3.connect(dbstr)

    cur = con.cursor()

    cur.execute("select * from student")

    studentList = cur.fetchall()

    cur.close()

    con.close()

    print(studentList)


    num = sid.get()

    flag = 0

    #if num.isnumeric() == False:

    if num.isnumeric() == False:

        showerror(title='提示', message='删除失敗')

    for i in range(len(studentList)):

        for item in studentList[i]:

            if int(num) == item:

                flag = 1

                con = sqlite3.connect(dbstr)

                cur = con.cursor()

                cur.execute("delete from student where sid = ?", (int(num),))

                con.commit()

                cur.close()

                con.close()

                break

    if flag == 1:

        showinfo(title='提示', message='删除成功!')

    else:

        showerror(title='提示', message='删除失敗')


    x = dataTreeview.get_children()

    for item in x:

        dataTreeview.delete(item)


    con = sqlite3.connect(dbstr)

    cur = con.cursor()

    cur.execute("select * from student")

    lst = cur.fetchall()

    for item in lst:

        dataTreeview.insert("", 1, text="line1", values=item)

    cur.close()

    con.close()



Button(root, text="顯示所有資料", command=showAllInfo).place(relx=0.2, rely=0.2, width=100)

Button(root, text="新增資料", command=appendInfo).place(relx=0.4, rely=0.2, width=100)

Button(root, text="删除資料", command=deleteInfo).place(relx=0.6, rely=0.2, width=100)

Button(root, text="建立資料庫", command=createTable).place(relx=0.8, rely=0.2, width=100)




dataTreeview = ttk.Treeview(root, show='headings', column=('sid', 'name', 'phone', 'address'))

dataTreeview.column('sid', width=150, anchor="center")

dataTreeview.column('name', width=150, anchor="center")

dataTreeview.column('phone', width=150, anchor="center")

dataTreeview.column('address', width=150, anchor="center")


dataTreeview.heading('sid', text='學號')

dataTreeview.heading('name', text='姓名')

dataTreeview.heading('phone', text='電話')

dataTreeview.heading('address', text='地址')


dataTreeview.place(rely=0.3, relwidth=0.97)


2022年11月28日 星期一

Python TKinter Excel + Sqlite

 Python TKinter Excel + Sqlite






import tkinter

from tkinter import ttk

from tkinter import messagebox


import sqlite3

import os

import openpyxl


def enter_data():

    accepted = accept_var.get()

    

    if accepted=="Accepted":

        # User info

        firstname = first_name_entry.get()

        lastname = last_name_entry.get()

        

        if firstname and lastname:

            title = title_combobox.get()

            age = age_spinbox.get()

            nationality = nationality_combobox.get()

            

            # Course info

            registration_status = reg_status_var.get()

            numcourses = numcourses_spinbox.get()

            numsemesters = numsemesters_spinbox.get()

            

            print("First name: ", firstname, "Last name: ", lastname)

            print("Title: ", title, "Age: ", age, "Nationality: ", nationality)

            print("# Courses: ", numcourses, "# Semesters: ", numsemesters)

            print("Registration status", registration_status)

            print("------------------------------------------")

            

            # Create Table

            conn = sqlite3.connect('data.db')

            table_create_query = '''CREATE TABLE IF NOT EXISTS Student_Data 

                    (firstname TEXT, lastname TEXT, title TEXT, age INT, nationality TEXT, 

                    registration_status TEXT, num_courses INT, num_semesters INT)

            '''

            conn.execute(table_create_query)

            

            # Insert Data

            data_insert_query = '''INSERT INTO Student_Data (firstname, lastname, title, 

            age, nationality, registration_status, num_courses, num_semesters) VALUES 

            (?, ?, ?, ?, ?, ?, ?, ?)'''

            data_insert_tuple = (firstname, lastname, title,

                                  age, nationality, registration_status, numcourses, numsemesters)

            cursor = conn.cursor()

            cursor.execute(data_insert_query, data_insert_tuple)

            conn.commit()

            conn.close()

            

            

            filepath = "data.xlsx"

            

            if not os.path.exists(filepath):

                workbook = openpyxl.Workbook()

                sheet = workbook.active

                heading = ["First Name", "Last Name", "Title", "Age", "Nationality",

                           "# Courses", "# Semesters", "Registration status"]

                sheet.append(heading)

                workbook.save(filepath)

            workbook = openpyxl.load_workbook(filepath)

            sheet = workbook.active

            sheet.append([firstname, lastname, title, age, nationality, numcourses,

                          numsemesters, registration_status])

            workbook.save(filepath)

            

                

        else:

            tkinter.messagebox.showwarning(title="Error", message="First name and last name are required.")

    else:

        tkinter.messagebox.showwarning(title= "Error", message="You have not accepted the terms")


window = tkinter.Tk()

window.title("Data Entry Form")


frame = tkinter.Frame(window)

frame.pack()


# Saving User Info

user_info_frame =tkinter.LabelFrame(frame, text="User Information")

user_info_frame.grid(row= 0, column=0, padx=20, pady=10)


first_name_label = tkinter.Label(user_info_frame, text="First Name")

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

last_name_label = tkinter.Label(user_info_frame, text="Last Name")

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


first_name_entry = tkinter.Entry(user_info_frame)

last_name_entry = tkinter.Entry(user_info_frame)

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

last_name_entry.grid(row=1, column=1)


title_label = tkinter.Label(user_info_frame, text="Title")

title_combobox = ttk.Combobox(user_info_frame, values=["", "Mr.", "Ms.", "Dr."])

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

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


age_label = tkinter.Label(user_info_frame, text="Age")

age_spinbox = tkinter.Spinbox(user_info_frame, from_=18, to=110)

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

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


nationality_label = tkinter.Label(user_info_frame, text="Nationality")

nationality_combobox = ttk.Combobox(user_info_frame, values=["Africa", "Antarctica", "Asia", "Europe", "North America", "Oceania", "South America"])

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

nationality_combobox.grid(row=3, column=1)


for widget in user_info_frame.winfo_children():

    widget.grid_configure(padx=10, pady=5)


# Saving Course Info

courses_frame = tkinter.LabelFrame(frame)

courses_frame.grid(row=1, column=0, sticky="news", padx=20, pady=10)


registered_label = tkinter.Label(courses_frame, text="Registration Status")


reg_status_var = tkinter.StringVar(value="Not Registered")

registered_check = tkinter.Checkbutton(courses_frame, text="Currently Registered",

                                       variable=reg_status_var, onvalue="Registered", offvalue="Not registered")


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

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


numcourses_label = tkinter.Label(courses_frame, text= "# Completed Courses")

numcourses_spinbox = tkinter.Spinbox(courses_frame, from_=0, to='infinity')

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

numcourses_spinbox.grid(row=1, column=1)


numsemesters_label = tkinter.Label(courses_frame, text="# Semesters")

numsemesters_spinbox = tkinter.Spinbox(courses_frame, from_=0, to="infinity")

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

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


for widget in courses_frame.winfo_children():

    widget.grid_configure(padx=10, pady=5)


# Accept terms

terms_frame = tkinter.LabelFrame(frame, text="Terms & Conditions")

terms_frame.grid(row=2, column=0, sticky="news", padx=20, pady=10)


accept_var = tkinter.StringVar(value="Not Accepted")

terms_check = tkinter.Checkbutton(terms_frame, text= "I accept the terms and conditions.",

                                  variable=accept_var, onvalue="Accepted", offvalue="Not Accepted")

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


# Button

button = tkinter.Button(frame, text="Enter data", command= enter_data)

button.grid(row=3, column=0, sticky="news", padx=20, pady=10)

 

window.mainloop()


 

2022年11月27日 星期日

Python Tkinter-data-entry

 Python Tkinter-data-entry




(1)

import tkinter

from tkinter import ttk

from tkinter import messagebox


w= tkinter.Tk()

w.title("Data Entry Form")


frame = tkinter.Frame(w)

frame. Pack()


w.mainloop()



(2)

import tkinter

from tkinter import ttk

from tkinter import messagebox


w= tkinter.Tk()

w.title("Data Entry Form")


frame = tkinter.Frame(w)

frame.pack()


# Saving User Info

user_info_frame =tkinter.LabelFrame(frame, text="User Information")

user_info_frame.grid(row= 0, column=0, padx=20, pady=10)


first_name_label = tkinter.Label(user_info_frame, text="First Name")

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

last_name_label = tkinter.Label(user_info_frame, text="Last Name")

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


first_name_entry = tkinter.Entry(user_info_frame)

last_name_entry = tkinter.Entry(user_info_frame)

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

last_name_entry.grid(row=1, column=1)


w.mainloop()


(3)

import tkinter

from tkinter import ttk

from tkinter import messagebox


w= tkinter.Tk()

w.title("Data Entry Form")


frame = tkinter.Frame(w)

frame.pack()


# Saving User Info

user_info_frame =tkinter.LabelFrame(frame, text="User Information")

user_info_frame.grid(row= 0, column=0, padx=20, pady=10)


first_name_label = tkinter.Label(user_info_frame, text="First Name")

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

last_name_label = tkinter.Label(user_info_frame, text="Last Name")

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


first_name_entry = tkinter.Entry(user_info_frame)

last_name_entry = tkinter.Entry(user_info_frame)

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

last_name_entry.grid(row=1, column=1)


title_label = tkinter.Label(user_info_frame, text="Title")

title_combobox = ttk.Combobox(user_info_frame, values=["", "Mr.", "Ms.", "Dr."])

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

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


age_label = tkinter.Label(user_info_frame, text="Age")

age_spinbox = tkinter.Spinbox(user_info_frame, from_=18, to=110)

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

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


nationality_label = tkinter.Label(user_info_frame, text="Nationality")

nationality_combobox = ttk.Combobox(user_info_frame, values=["Africa", "Antarctica", "Asia", "Europe", "North America", "Oceania", "South America"])

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

nationality_combobox.grid(row=3, column=1)


for widget in user_info_frame.winfo_children():

    widget.grid_configure(padx=10, pady=5)

    

 

w.mainloop()


(4)

import tkinter

from tkinter import ttk

from tkinter import messagebox


w= tkinter.Tk()

w.title("Data Entry Form")


frame = tkinter.Frame(w)

frame.pack()


# Saving User Info

user_info_frame =tkinter.LabelFrame(frame, text="User Information")

user_info_frame.grid(row= 0, column=0, padx=20, pady=10)


first_name_label = tkinter.Label(user_info_frame, text="First Name")

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

last_name_label = tkinter.Label(user_info_frame, text="Last Name")

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


first_name_entry = tkinter.Entry(user_info_frame)

last_name_entry = tkinter.Entry(user_info_frame)

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

last_name_entry.grid(row=1, column=1)


title_label = tkinter.Label(user_info_frame, text="Title")

title_combobox = ttk.Combobox(user_info_frame, values=["", "Mr.", "Ms.", "Dr."])

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

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


age_label = tkinter.Label(user_info_frame, text="Age")

age_spinbox = tkinter.Spinbox(user_info_frame, from_=18, to=110)

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

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


nationality_label = tkinter.Label(user_info_frame, text="Nationality")

nationality_combobox = ttk.Combobox(user_info_frame, values=["Africa", "Antarctica", "Asia", "Europe", "North America", "Oceania", "South America"])

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

nationality_combobox.grid(row=3, column=1)


for widget in user_info_frame.winfo_children():

    widget.grid_configure(padx=10, pady=5)


# Saving Course Info

courses_frame = tkinter.LabelFrame(frame)

courses_frame.grid(row=1, column=0, sticky="news", padx=20, pady=10)


registered_label = tkinter.Label(courses_frame, text="Registration Status")


reg_status_var = tkinter.StringVar(value="Not Registered")

registered_check = tkinter.Checkbutton(courses_frame, text="Currently Registered",

                                       variable=reg_status_var, onvalue="Registered", offvalue="Not registered")


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

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


numcourses_label = tkinter.Label(courses_frame, text= "# Completed Courses")

numcourses_spinbox = tkinter.Spinbox(courses_frame, from_=0, to='infinity')

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

numcourses_spinbox.grid(row=1, column=1)


numsemesters_label = tkinter.Label(courses_frame, text="# Semesters")

numsemesters_spinbox = tkinter.Spinbox(courses_frame, from_=0, to="infinity")

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

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


for widget in courses_frame.winfo_children():

    widget.grid_configure(padx=10, pady=5)


 # Accept terms

terms_frame = tkinter.LabelFrame(frame, text="Terms & Conditions")

terms_frame.grid(row=2, column=0, sticky="news", padx=20, pady=10)


accept_var = tkinter.StringVar(value="Not Accepted")

terms_check = tkinter.Checkbutton(terms_frame, text= "I accept the terms and conditions.",

                                  variable=accept_var, onvalue="Accepted", offvalue="Not Accepted")

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


 

w.mainloop()


(5)

import tkinter

from tkinter import ttk

from tkinter import messagebox


def enter_data():

    accepted = accept_var.get()

    

    if accepted=="Accepted":

        # User info

        firstname = first_name_entry.get()

        lastname = last_name_entry.get()

        

        if firstname and lastname:

            title = title_combobox.get()

            age = age_spinbox.get()

            nationality = nationality_combobox.get()

            

            # Course info

            registration_status = reg_status_var.get()

            numcourses = numcourses_spinbox.get()

            numsemesters = numsemesters_spinbox.get()

            

            print("First name: ", firstname, "Last name: ", lastname)

            print("Title: ", title, "Age: ", age, "Nationality: ", nationality)

            print("# Courses: ", numcourses, "# Semesters: ", numsemesters)

            print("Registration status", registration_status)

            print("------------------------------------------")

        else:

            tkinter.messagebox.showwarning(title="Error", message="First name and last name are required.")

    else:

        tkinter.messagebox.showwarning(title= "Error", message="You have not accepted the terms")


window = tkinter.Tk()

window.title("Data Entry Form")


frame = tkinter.Frame(window)

frame.pack()


# Saving User Info

user_info_frame =tkinter.LabelFrame(frame, text="User Information")

user_info_frame.grid(row= 0, column=0, padx=20, pady=10)


first_name_label = tkinter.Label(user_info_frame, text="First Name")

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

last_name_label = tkinter.Label(user_info_frame, text="Last Name")

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


first_name_entry = tkinter.Entry(user_info_frame)

last_name_entry = tkinter.Entry(user_info_frame)

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

last_name_entry.grid(row=1, column=1)


title_label = tkinter.Label(user_info_frame, text="Title")

title_combobox = ttk.Combobox(user_info_frame, values=["", "Mr.", "Ms.", "Dr."])

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

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


age_label = tkinter.Label(user_info_frame, text="Age")

age_spinbox = tkinter.Spinbox(user_info_frame, from_=18, to=110)

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

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


nationality_label = tkinter.Label(user_info_frame, text="Nationality")

nationality_combobox = ttk.Combobox(user_info_frame, values=["Africa", "Antarctica", "Asia", "Europe", "North America", "Oceania", "South America"])

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

nationality_combobox.grid(row=3, column=1)


for widget in user_info_frame.winfo_children():

    widget.grid_configure(padx=10, pady=5)


# Saving Course Info

courses_frame = tkinter.LabelFrame(frame)

courses_frame.grid(row=1, column=0, sticky="news", padx=20, pady=10)


registered_label = tkinter.Label(courses_frame, text="Registration Status")


reg_status_var = tkinter.StringVar(value="Not Registered")

registered_check = tkinter.Checkbutton(courses_frame, text="Currently Registered",

                                       variable=reg_status_var, onvalue="Registered", offvalue="Not registered")


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

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


numcourses_label = tkinter.Label(courses_frame, text= "# Completed Courses")

numcourses_spinbox = tkinter.Spinbox(courses_frame, from_=0, to='infinity')

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

numcourses_spinbox.grid(row=1, column=1)


numsemesters_label = tkinter.Label(courses_frame, text="# Semesters")

numsemesters_spinbox = tkinter.Spinbox(courses_frame, from_=0, to="infinity")

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

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


for widget in courses_frame.winfo_children():

    widget.grid_configure(padx=10, pady=5)


# Accept terms

terms_frame = tkinter.LabelFrame(frame, text="Terms & Conditions")

terms_frame.grid(row=2, column=0, sticky="news", padx=20, pady=10)


accept_var = tkinter.StringVar(value="Not Accepted")

terms_check = tkinter.Checkbutton(terms_frame, text= "I accept the terms and conditions.",

                                  variable=accept_var, onvalue="Accepted", offvalue="Not Accepted")

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


# Button

button = tkinter.Button(frame, text="Enter data", command= enter_data)

button.grid(row=3, column=0, sticky="news", padx=20, pady=10)

 

window.mainloop()



源自於 https://github.com/codefirstio/tkinter-data-entry/blob/main/sqlite-data-entry/main.py


2022年11月25日 星期五

Tkinter - the Python interface for Tk

Tkinter - the Pyton interface for Tk

In this chapter

Page
Description
1. Labels in TkinterTkinter Labels - GUI Programming with Python: Simple Examples
2. Message widget in TkinterThe tkinter message widget under Python.
3. Buttons in TkinterTk tutorial: Using Buttons in Tkinter under Python.
4. Variable Classes in TkinterIntroducing Tkinter Variable Classes: StringVar, IntVar, DoubleVar and BooleanVar
5. Radio Buttons in TkinterThis chapter deals with Radiobuttons in Tk and Tkinter under Python.
6. Checkboxes in TkinterCheckboxes in Tkinter with example applications
7. Entry Widgets in TkinterTutorial on Tkinter: Communication with the User by using Entry Widgets
8. Canvas Widgets in TkinterTutorial on Tkinter: Canvas Widgets
9. Sliders in TkinterIntroduction to Sliders in Tkinter
10. Text Widget in TkinterText input for web applications with Text widgets in Tkinter
11. Dialogs in TkinterIntroduction to the standard dialogues of Tkinter.
12. Layout Management in TkinterLayout management under Tkinter and Python using pack, grid and place; GUI Programming with Python:
13. The Game of Life in PythonAn implementation of game of Life. The focus is on teaching Python and Tkinter. GUI Programming with Python: Not really a Game:
14. Bulls and Cows / Mastermind in TkinterImplemenation of Bulls and Cows, also known as Mastermind in Tk /Tkinter
15. Menus in TkinterDesigning and creating Menus in Tkinter GUI Programming with Python:
16. Events and Binds in TkinterTutorial and Introduction on Tkinter: Using Events and Binds, GUI Programming with Python:
源自於 https://python-course.eu/tkinter/

2024_09 作業3 以Node-Red 為主

 2024_09 作業3  (以Node-Red 為主  Arduino 可能需要配合修改 ) Arduino 可能需要修改的部分 1)mqtt broker  2) 主題Topic (發行 接收) 3) WIFI ssid , password const char br...