آموزش برنامهنویسی سیستم با پایتون
به منظور ایجاد برنامههای سیستمی با رابطه کاربری گرافیکی از کتابخانهای با نام Tkinter استفاده میکنیم. کتابخانه Tkinter به صورت پیش فرض در هنگام نصب IDE پایتون نصب میشود و نیازی به نصب مجدد آن نمی باشد. اما در صورتی که IDE پایتون به صورت سفارشی نصب شده باشد و این کتابخانه وجود نداشته باشد میتوانیم با اجرای دستور زیر در محیط ترمینال این کتابخانه را نصب نماییم.
pip install tkinter
طریقهی ایجاد Window
import tkinter as tk
win = tk.Tk()
win.title(“First Program”)
win.resizable(0, 0)
win.mainloop()
طریقه ایجاد کنترل Label
import tkinter as tk
win = tk.Tk()
win.title(“First Program”)
label_01 = tk.Label(text=”Enter Your Name : “, foreground=”#A7E3ED”,
background=”#000202″, width=20, height=1, font=(“Times New Roman”, 10))
label_01.pack()
win.mainloop()
طریقه ایجاد کنترل Button
import tkinter as tk
win = tk.Tk()
win.title(“First Program”)
button_01 = tk.Button(text=”Submit”, width=20, height=1, bg=”#000202″, fg=”#A7E3ED”)
button_01.pack()
win.mainloop()
طریقه ایجاد و استفاده از کنترل Combobox
در برنامه نوشته شده آیتمهای Combobox (نامهای ماههای سال میلادی) از یک جدول به نام month_name_table که در پایگاه داده Database_Test ذخیره شده است واکشی میشود. در قسمتی از کد که کامنت شده است امکان استخراج نامهای ماههای سال میلادی به صورت دیگر و با به کارگیری کلاس month_name کتابخانه calendat ممکن شده است. جدول month_name_table را با استفاده از پرس و جوی زیر میتوان در SQL Server ایجاد نمود.
create table month_name_table
(
Id bigint not null,
Month_Name nvarchar(50) null,
primary key (Id)
)
سورس کد پایتون
import pyodbc
from tkinter import *
import tkinter as tk
from tkinter import ttk
from calendar import month_name
from tkinter.messagebox import showinfo
def month_changed(event):
showinfo(title=”Result”, message=f”You Selected {selected_month.get()} Month”)
win = tk.Tk()
win.title(“ComboBox”)
win.geometry(“200×50″)
win.resizable(0, 0)
label_01 = tk.Label(text=”Select Month”, foreground=”black”,
background=”white”, width=10, height=1, font=(“arial”, 10), anchor=”n”, justify=”center”, relief=GROOVE)
label_01.pack()
label_01.place(relx=0.06, rely=0.3)
selected_month = tk.StringVar()
combobox_01 = ttk.Combobox(win, width=10, textvariable=selected_month, justify=”center”)
combobox_01.option_add(“*TCombobox*Listbox.Justify”, “center”)
#combobox_01[“values”] = [month_name[m][0:3] for m in range(1, 13)]
connection_string = “Driver=SQL Server;Server=ESMAEILI-PC;Database=Database_Test;Uid=sa;Pwd=Password;”
connection = pyodbc.connect(connection_string)
sql_command = “SELECT Month_Name FROM month_name_table”
r = connection.cursor().execute(sql_command)
my_values = []
for record in r:
my_values.append(record[0])
combobox_01.configure(values=my_values)
connection.commit()
connection.close()
combobox_01.current(0)
combobox_01.grid(column=0, row=0)
combobox_01.pack()
combobox_01.place(relx=0.52, rely=0.32)
combobox_01.bind(“<<ComboboxSelected>>”, month_changed)
win.mainloop()
فایل برنامه نوشته شده را میتوانید از اینجا دانلود نمایید.
برنامه ذخیره کردن دادهها در پایگاه داده SQL Server و نمایش آنها در Treeview
در برنامه نوشته شده، دادههای دریافت شده توسط رابطه کاربری در جدولی به نام phone_book ذخیره میشود. سپس این دادهها از جدول phone_book واکشی و در ویجت Treeview نمایش داده میشود. در این برنامه، دو دکمه به نامهای Up و Down به ترتیب برای جابهجایی هر رکورد دلخواه نمایش داده شده در ویجت Treeview به سمت بالا و پایین در نظر گرفته شده است. همچنین با کلیک بر روی هر رکورد دلخواه نمایش داده شده در ویجت Treeview، مقادیر آن رکورد در Textbox نمایش داده میشود. در اینجا جدول phone_book را با استفاده از پرس و جوی زیر میتوان در SQL Server ایجاد نمود.
create table phone_book
(
Id bigint not null,
Fullname nvarchar(50) null,
Phone nvarchar(50) null,
primary key (Id)
)
سورس کد پایتون
# pip install pyodbc
# pip install tkinter
import pyodbc
import tkinter as tk
from tkinter import *
from tkinter import ttk
win = tk.Tk()
frame_01 = ttk.Treeview(win, selectmode=’browse’)
frame_01.pack(side=LEFT)
frame_01.place(relx=0.01, rely=0.4)
frame_01 = ttk.Treeview(frame_01, height=4)
verscrlbar = ttk.Scrollbar(win, orient=”vertical”, command=frame_01.yview)
verscrlbar.pack(side=’left’, fill=’x’)
verscrlbar.place(relx=0.01, rely=0.55)
frame_01.configure(xscrollcommand=verscrlbar.set)
frame_01[‘columns’] = (‘Fullname’, ‘Phone’)
frame_01.column(“#0”, width=0, stretch=NO)
frame_01.column(“Fullname”, anchor=CENTER, width=100)
frame_01.column(“Phone”, anchor=CENTER, width=100)
frame_01.heading(“#0″, text=””, anchor=CENTER)
frame_01.heading(“Fullname”, text=”Fullname”, anchor=CENTER)
frame_01.heading(“Phone”, text=”Phone”, anchor=CENTER)
# === Functions
def my_up():
rows = frame_01.selection()
for row in rows:
frame_01.move(row, frame_01.parent(row), frame_01.index(row)-1)
def my_down():
rows = frame_01.selection()
for row in reversed(rows):
frame_01.move(row, frame_01.parent(row), frame_01.index(row)+1)
def refresh():
global i
connection_string = “Driver=SQL Server;Server=ESMAEILI-PC;Database=Database_Test;Uid=sa;Pwd=Password;”
connection = pyodbc.connect(connection_string)
sql_command = “SELECT * FROM phone_book”
r = connection.cursor().execute(sql_command)
i = 1
for row in frame_01.get_children():
frame_01.delete(row)
i = i + 1
i = 1
for record in r:
frame_01.insert(parent=”, index=”end”, iid=i, text=””, values=(record[1], record[2]))
i = i + 1
connection.commit()
connection.close()
frame_01.pack()
style = ttk.Style()
style.theme_use(“default”)
style.map(“Treeview”)
def save():
connection_string = “Driver=SQL Server;Server=ESMAEILI-PC;Database=Database_Test;Uid=sa;Pwd=Password;”
connection = pyodbc.connect(connection_string)
Fullname = textbox_01.get(“1.0”, “end-1c”)
Phone = textbox_02.get(“1.0”, “end-1c”)
sql_command = “EXEC sp_save @Fullname =?, @Phone=?”
connection.cursor().execute(sql_command, (Fullname, Phone))
connection.commit()
connection.close()
textbox_01.delete(“1.0”, “end”)
textbox_02.delete(“1.0”, “end”)
label_03.config(fg=”green”)
my_string.set(“Data are saving …”)
label_03.after(3000, lambda: my_string.set(“”))
i=1
refresh()
def select(e):
select_record()
def select_record():
selected_index = frame_01.focus()
x = frame_01.item(selected_index, “values”)
textbox_03.delete(“1.0”, “end”)
textbox_03.tag_configure(“center”, justify=’center’)
textbox_03.insert(“1.0”, x[0])
textbox_03.tag_add(“center”, “1.0”, “end”)
textbox_04.delete(“1.0”, “end”)
textbox_04.tag_configure(“center”, justify=’center’)
textbox_04.insert(“1.0”, x[1])
textbox_04.tag_add(“center”, “1.0”, “end”)
def my_exit():
win.destroy()
# === Windows
win.title(“Phone Book”)
win.geometry(“400×200″)
win.resizable(0, 0)
# === Label
label_01 = tk.Label(text=”Fullname”, foreground=”black”,
background=”white”, width=9, height=1, font=(“arial”, 10), anchor=”n”, justify=”center”, relief=GROOVE)
label_01.pack()
label_01.place(relx=0.01, rely=0.02)
label_02 = tk.Label(text=”Phone”, foreground=”black”,
background=”white”, width=9, height=1, font=(“Lora”, 10), anchor=”n”, justify=”center”, relief=GROOVE)
label_02.pack()
label_02.place(relx=0.01, rely=0.14)
my_string = tk.StringVar()
label_03 = tk.Label(win, textvariable=my_string, background=”white”, width=15, height=2, font=(“arial”, 10), anchor=”center”, justify=”center”, relief=GROOVE)
label_03.pack()
label_03.place(relx=0.56, rely=0.035)
# === Textbox
textbox_01 = tk.Text(win, height=1, width=15)
textbox_01.pack()
textbox_01.place(relx=0.21, rely=0.02)
textbox_02 = tk.Text(win, height=1, width=15)
textbox_02.pack()
textbox_02.place(relx=0.21, rely=0.14)
textbox_03 = tk.Text(win, height=1, width=10)
textbox_03.pack()
textbox_03.place(relx=0.53, rely=0.53)
textbox_04 = tk.Text(win, height=1, width=10)
textbox_04.pack()
textbox_04.place(relx=0.75, rely=0.53)
# === Button
button_01 = tk.Button(win, text=”Save”, command=save, height=1, width=10)
button_01.pack()
button_01.place(relx=0.01, rely=0.26)
button_02 = tk.Button(win, text=”Select”, command=select_record, height=1, width=10)
button_02.pack()
button_02.place(relx=0.22, rely=0.26)
button_03 = tk.Button(win, text=”Exit”, command=my_exit, height=1, width=10)
button_03.pack()
button_03.place(relx=0.43, rely=0.26)
button_04 = tk.Button(win, text=”Up”, command=my_up, height=1, width=5)
button_04.pack()
button_04.place(relx=0.64, rely=0.26)
button_05 = tk.Button(win, text=”Down”, command=my_down, height=1, width=5)
button_05.pack()
button_05.place(relx=0.76, rely=0.26)
#=== Frame
refresh()
# For Double Click
frame_01.bind(“<Double-1>”, select)
if __name__ == ‘__main__’:
win.mainloop()
فایل برنامه نوشته شده را میتوانید از اینجا دانلود نمایید.
برنامه نمایش تعداد سطرهای یک جدول
import pyodbc
from tkinter import *
import tkinter as tk
win = tk.Tk()
win.title(“Row Count”)
win.geometry(“200×50″)
win.resizable(0, 0)
label_01 = tk.Label(text=”Row Count”, foreground=”black”,
background=”white”, width=10, height=1, font=(“arial”, 10), anchor=”n”, justify=”center”, relief=GROOVE)
label_01.pack()
label_01.place(relx=0.06, rely=0.3)
textbox_01 = tk.Text(win, height=1, width=10)
textbox_01.pack()
textbox_01.place(relx=0.52, rely=0.32)
connection_string = “Driver=SQL Server;Server=ESMAEILI-PC;Database=Database_Test;Uid=sa;Pwd=Password;”
connection = pyodbc.connect(connection_string)
sql_command = “SELECT count(*) FROM month_name_table”
out_put= connection.cursor().execute(sql_command)
count = out_put.fetchone()[0]
textbox_01.delete(“1.0”, “end”)
textbox_01.tag_configure(“center”, justify=’center’)
textbox_01.insert(“1.0”, count)
connection.commit()
connection.close()
win.mainloop()
فایل برنامه نوشته شده را میتوانید از اینجا دانلود نمایید.
پنجره ورود به برنامه
در برنامه نوشته شده دو پنجره به نامهای win_under و win_top در نظر گرفته شده است. پنجره بالایی (win_top) که تحت نام پنجره لاگین هم شناخته میشود نام کاربری و کلمه عبور را از کاربر درخواست میکند. در اینجا در صورتی که کاربر نام کاربری و کلمه عبور را درست وارد نماید پنجره لاگین بسته شده و پنجره زیرین که محتوایات اصلی برنامه در آنجا قرار دارد نمایش داده میشود. تا زمانی که کابر نام کاربری و کلمه عبور را درست وارد نکند پنجره زیرین قابل دسترس نبوده و کلیهی ویجتهای آن غیر فعال میباشد.
from tkinter import * import sys import tkinter as tk win_under = tk.Tk() win_under.title("Main Windows") app_width_under = 400 app_height_under = 200 screen_width = win_under.winfo_screenwidth() screen_height = win_under.winfo_screenheight() x_under = (screen_width/2)-(app_width_under/2) y_under = (screen_height/2)-(app_height_under/2) win_under.geometry(f"{app_width_under}x{app_height_under}+{int(x_under)}+{int(y_under)}") win_top = tk.Toplevel() win_under.resizable(0, 0) win_top.geometry("200x100") win_top.resizable(0, 0) win_under.eval(f'tk::PlaceWindow {str(win_top)} center') label_01 = tk.Label(win_top, text="Username", foreground="black", background="white", width=8, height=1, font=("arial", 10), anchor="n", justify="center", relief=GROOVE) label_01.pack() label_01.place(relx=0.05, rely=0.1) label_02 = tk.Label(win_top, text="Password", foreground="black", background="white", width=8, height=1, font=("arial", 10), anchor="n", justify="center", relief=GROOVE) label_02.pack() label_02.place(relx=0.05, rely=0.35) label_03 = tk.Label(win_under, text="Enter Your Age", foreground="black", background="white", width=20, height=1, font=("arial", 10), anchor="n", justify="center", relief=GROOVE) label_03.pack() label_03.place(relx=0.05, rely=0.1) entry_01 = Entry(win_top) entry_01.pack() entry_01.place(relx=0.42, rely=0.1, width=100, height=20) entry_02 = Entry(win_top, show="☼") entry_02.pack() entry_02.place(relx=0.42, rely=0.33, width=100) button_01 = Button(win_top, text="Login", command=lambda: my_login()) button_01.pack() button_01.place(relx=0.042, rely=0.6) button_02 = Button(win_top, text="Cancel", command=lambda: my_exit()) button_02.pack() button_02.place(relx=0.26, rely=0.6) textbox_01 = tk.Text(win_under, height=1, width=22) textbox_01.pack() textbox_01.place(relx=0.48, rely=0.1) for child in win_under.winfo_children(): try: if child.widgetName != 'frame': child.configure(state='disabled') except Exception as e: print(e) def my_login(): if entry_01.get() == "username" and entry_02.get() == "password": win_under.deiconify() win_top.destroy() for child in win_under.winfo_children(): try: if child.widgetName != 'frame': child.configure(state='normal') except Exception as e: print(e) else: entry_01.delete(0, "end") entry_02.delete(0, "end") def my_exit(): win_top.destroy() win_under.destroy() sys.exit() win_under.mainloop()
فایل برنامه نوشته شده را میتوانید از اینجا دانلود نمایید.