การใช้งาน Widgets ต่างใน Tkinter
ในการพัฒนาโปรแกรมแสดงต่างผลแสดงผล และรับข้อมูล (GUI) บน Python ในหัวข้อนี้จะพัฒนาโปรแกรมโดยใช้โมดูล Tkinter เป็นโมดูลที่พัฒนามาจาก Tk GUI Toolkit ซึ่งต้องทำการติดตั้งให้เรียบร้อยก่อนจึงจะสามารถใช้งานได้ ซึ่งในโมดูล Tkinter จะมี Widgets ให้ใช้งานมากมาย เช่น Button, Label, Frame, Checkbox, Scrollbars เป็นต้น ในการเรียกใช้งาน Widgets จะเรียกใช้งานด้วยคำสั่งรูปแบบต่างๆ ซึ่งจะสามารถศึกษาเรียนรู้ได้ตามรายละเอียดต่อไปนี้
👉การสร้างหน้าต่างแสดงผล ด้วย โมดูล Tkinter จะเริ่มต้นจากการ 1) นำเข้าไลบรารี tkinter และสร้างคลาส Tk โดยใช้คำสั่ง from tkinter import Tk 2) สร้างหน้าต่างแรกของโปรแกรม ซึ่งเป็น root หรือเป็นหน้าต่างหลัง ของโปรแกรม โดยใช้คำสั่ง root = Tk() 3) กำหนดชื่อของ title ของหน้าต่างโปรแกรมโดยใช้คำสั่ง root.title("First program") 4) กำหนดขนาดหน้าต่าง และตำแหน่งของหน้าต่างโดยใช้คำสั่ง root.geometry ("500x500+100+100") และ 5) สั่งให้โปรแกรมวนลูปรับคำสั่งจากผู้ใช้งานไปเรื่อยๆ จนกว่าจะปิดโปรแกรม ด้วยคำสั่ง root.mainloop()
from tkinter import Tk
# create the main windown
root = tk.Tk()
root.title("First program") # set title of windown
root.geometry("500x500+100+100") # set size and position of windown
root.mainloop()
เมื่อรันโปรแกรมแล้วผลลัพท์ที่ได้
👉การแสดงผลตัวหนังสือหรือข้อความต่างๆ (Label) จะมีขั้นตอนการดังต่อไปนี้ 1) กำหนดคลาสเพิ่มโดยใช้คำสั่ง from tkinter import Tk, Label 2) สร้างหน้าต่างแสดงผล 3) ใช้คำสั่ง Label(root, text="Automationlearn", bg="red", font=('Courier 22 bold'), width=15, height=1).place(x=30, y=100) เพื่อทดลองแสดงข้อความในหน้าต่างแสดงผล
from tkinter import Tk, Label
# create the main windown
root = tk.Tk()
root.title("First program") # set title of windown
root.geometry("500x500+100+100") # set size and position of windown
Label(root, text="Automationlearn", bg="red", font=('Courier 22 bold'), width=15, height=1).place(x=30, y=100)
root.mainloop()
เมื่อรันโปรแกรมแล้วผลลัพท์ที่ได้
👉การสร้างตัวรับค่า slide bar แสดงผลออกเป็นข้อความ Label จะมีขั้นตอนการดังต่อไปนี้
from tkinter import Tk, Canvas, Button, Scale, HORIZONTAL, Label
def update_value(val)
label.config(text=f"Value: {val}") # Correctly update the label instance
# Create main window
root = tk.Tk()
root.title("Slider Example")
root.geometry("700x700+300+300") # User prefers 500x500 window
# Create a slider
slider = Scale(root, from_=0, to=100, orient=HORIZONTAL, length=300, label="Input 1", command=update_value, font=('Courier 15 bold'))
slider.place(x=200, y=100)
# Create a label to display the value
label = Label(root, text="Value: 0", bg="red", font=('Courier 25 bold'), width=10, height=1)
label.place(x=250, y=245)
# Run the application
root.mainloop()
👉การสร้างตัวรับค่า slide bar 2 ตัว นำค่าบวกกัน และแสดงผลออกเป็นข้อความ Label จะมีขั้นตอนการดังต่อไปนี้
from tkinter import Tk, Canvas, Button, Scale, HORIZONTAL, Label
def update_value(val):
total = slider1.get() + slider2.get()
label.config(text=f"Value: {total}")
# Create main window
root = tk.Tk()
root.title("Slider Example")
root.geometry("700x700+300+300")
# Create a slider1
slider1 = Scale(root, from_=0, to=100, orient=HORIZONTAL, length=300, label="Data1",command=update_value, font=('Courier 15 bold'))
slider1.place(x=200, y=100)
# Create a slider2
slider2 = Scale(root, from_=0, to=100, orient=HORIZONTAL, length=300, label="Data2",command=update_value, font=('Courier 15 bold'))
slider2.place(x=200, y=200)
# Create a label to display the value
label = Label(root, text="Value: 0", bg="red", font=('Courier 30 bold'), width=10, height=1)
label.place(x=240, y=345)
# Run the application
root.mainloop()
👉การสร้างปุ่ม (Button) จะมีขั้นตอนการดังต่อไปนี้
from tkinter import Tk, Canvas, Button, Scale, HORIZONTAL, Label
def cal():
total = slider1.get() + slider2.get()
label.config(text=f"Value: {total}")
# Create main window
root = tk.Tk()
root.title("Slider Example")
root.geometry("700x700+300+300")
# Create a slider1
slider1 = Scale(root, from_=0, to=100, orient=HORIZONTAL, length=300, label="Data1", font=('Courier 15 bold'))
slider1.place(x=200, y=100)
# Create a slider2
slider2 = Scale(root, from_=0, to=100, orient=HORIZONTAL, length=300, label="Data2", font=('Courier 15 bold'))
slider2.place(x=200, y=200)
# Create a button
button = Button(root, text ="Cal", font=('Courier 25 bold'), command = cal,width=5, height=1,bg="green")
button.place(x=300,y=450)
# Create a label to display the value
label = Label(root, text="Value: 0", bg="red", font=('Courier 30 bold'), width=10, height=1)
label.place(x=240, y=345)
# Run the application
root.mainloop()
👉การสร้างปุ่มหมุน (Knob) จะมีขั้นตอนการดังต่อไปนี้
from tkinter import Tk, Canvas, Button, Scale, HORIZONTAL, Label
from tkdial import Dial
def update_value():
total = dial1.get()
label.config(text=f"Value:{total}") # Correctly update the label instance
# Create main window
root = tk.Tk()
root.title("Knob Example")
root.geometry("700x700+300+300")
# Create a label to display the value
label = Label(root, text="Value: 0", bg="red", font=('Courier 30 bold'), width=11, height=1)
label.place(x=220, y=100)
# Create a knob
dial1 = Dial(master=root, color_gradient=("green", "red"),text_color="red", text="Value: ", command=update_value, unit_length=20, radius=50)
dial1.place(x=270, y=250)
# Run the application
root.mainloop()
from tkinter import Tk, Canvas, Button, Scale, HORIZONTAL, Label
from tkdial import Jogwheel
def update_value():
total = dial1.get()
label.config(text=f"Value:{total}") # Correctly update the label instance
# Create main window
root = Tk()
root.title("Knob Example")
root.geometry("700x700+300+300")
# Create a label to display the value
label = Label(root, text="Value: 0", bg="red", font=('Courier 30 bold'), width=11, height=1)
label.place(x=220, y=100)
# Create a knob
dial1 = Jogwheel(root, radius=200, fg="MediumOrchid", scale_color="white",
start=0, end=200, text="Volume: ", button_radius=10, command = update_value)
dial1.set_mark(0,50, "blue")
dial1.set_mark(50, 90, "green")
dial1.set_mark(90, 150, "orange")
dial1.set_mark(150, 200, "red")
dial1.place(x=250,y=200)
root.mainloop()
from tkinter import Tk
from tkdial import Jogwheel, Meter
# Create main window
root = Tk()
root.title("Knob Example")
root.geometry("700x700+300+300")
def update_value():
meter.set(int(dial.get()))
# Create a meter (Gauge)
meter = Meter(root, radius=200, start=0, end=200, border_width=5,
fg="black", text_color="white", start_angle=270, end_angle=-360,
text_font="DS-Digital 30", scale_color="black", axis_color="white",
needle_color="white")
meter.set_mark(1, 100, "#92d050")
meter.set_mark(105, 150, "yellow")
meter.set_mark(155, 196, "red")
meter.place(x=450, y=200)
# Create a knob (Jogwheel)
dial = Jogwheel(root, radius=200, fg="MediumOrchid", scale_color="white",
start=0, end=200, text="Volume: ", button_radius=10, command = update_value)
dial.set_mark(0,50, "blue")
dial.set_mark(50, 90, "green")
dial.set_mark(90, 150, "orange")
dial.set_mark(150, 200, "red")
dial.place(x=150,y=200)
root.mainloop()
from tkinter import Tk
from tkdial import Jogwheel, Meter
from tk_tools import Led
# Create main window
root = Tk()
root.title("Knob Example")
root.geometry("700x700+300+300")
def update_value():
meter.set(int(dial.get()))
if int(dial.get()) < 50:
led.to_green(on=True)
else:
led.to_green(on=False)
# Create a meter (Gauge)
meter = Meter(root, radius=200, start=0, end=200, border_width=5,
fg="black", text_color="white", start_angle=270, end_angle=-360,
text_font="DS-Digital 30", scale_color="black", axis_color="white",
needle_color="white")
meter.set_mark(1, 100, "#92d050")
meter.set_mark(105, 150, "yellow")
meter.set_mark(155, 196, "red")
meter.place(x=450, y=200)
# Create a knob (Jogwheel)
dial = Jogwheel(root, radius=200, fg="MediumOrchid", scale_color="white",
start=0, end=200, text="Volume: ", button_radius=10, command = update_value)
dial.set_mark(0,50, "blue")
dial.set_mark(50, 90, "green")
dial.set_mark(90, 150, "orange")
dial.set_mark(150, 200, "red")
dial.place(x=150,y=200)
# Create a LED
led = Led(root, size=50)
led.place(x=500,y=50)
root.mainloop()
👉การสร้างหลอด LED และการควบคุมสถานะด้วย Button Switch จะมีขั้นตอนการดังต่อไปนี้
from tkinter import Tk, Button
from tk_tools import Led
def onled():
led.to_green(on=True)
def offled():
led.to_green(on=False)
root = tk.Tk()
root.title("LED Example")
root.geometry("600x500+300+300")
# Create and display LED
led = Led(root, size=50)
led.place(x=250,y=80)
button = Button(root, text ="on", font=('Courier 20 bold'), command = onled,width=5, height=1,bg="gray")
button.place(x=150,y=400)
button = Button(root, text ="off", font=('Courier 20 bold'), command = offled,width=5, height=1,bg="gray")
button.place(x=350,y=400)
root.mainloop()
👉การสร้างหลอด LED กระพริบ และการควบคุมสถานะด้วย Button Switch จะมีขั้นตอนการดังต่อไปนี้
from tkinter import Tk, Button
from tk_tools import Led
root = Tk()
root.title("LED Blinking Example")
root.geometry("600x500+300+300")
blinking = False
led_state = False
def blink_led():
global led_state
if blinking:
led_state = not led_state # Toggle LED state
led.to_green(on=led_state) # Update LED
root.after(1000, blink_led) # Repeat every 1000ms (1 second)
def onled():
global blinking
if not blinking:
blinking = True
blink_led() # Start blinking
def offled():
global blinking, led_state
blinking = False # Stop blinking
led_state = False # Reset LED state
led.to_green(on=False) # Ensure LED is off
button_on = Button(root, text="ON", font=('Courier 20 bold'), command=onled, width=5, height=1, bg="gray")
button_on.place(x=150, y=400)
button_off = Button(root, text="OFF", font=('Courier 20 bold'), command=offled, width=5, height=1, bg="gray")
button_off.place(x=350, y=400)
led = Led(root, size=50)
led.place(x=250, y=80)
root.mainloop()
👉การสร้างตัวรับข้อมูลแบบ Text รับค่าด้วยการกดปุ่ม Button Switch จะมีขั้นตอนการดังต่อไปนี้
from tkinter import Tk, Button, Label, Text
from PIL import Image, ImageTk
# Create main window
root = tk.Tk()
root.title("Text Input Example")
root.geometry("700x500+300+300")
def printInput():
inp = inputtext.get(1.0, "end-1c")
lbl.config(text ="ได้รับข้อมูล: "+inp)
# TextBox Creation
inputtext = Text(root, bg="white", font=('Courier 20 bold'), width=11, height=1)
inputtext.pack(), inputtext.place(x=220, y=100)
# Button Creation
printButton = Button(root, text = "ตกลง", command = printInput, font=('Courier 15 bold'))
printButton.pack(), printButton.place(x=220, y=200)
# Label Creation
lbl = Label(root, text = "กรุณาป้อนข้อมูล", font=('Courier 15 bold'))
lbl.pack(), lbl.place(x=220, y=50)
# Label Creation
lbl = Label(root, text = "", font=('Courier 15 bold'))
lbl.pack(), lbl.place(x=220, y=150)
root.mainloop()
👉การสร้างตัวรับข้อมูลแบบ Text รับค่าด้วยการกดปุ่ม Enter บน Keyboard จะมีขั้นตอนการดังต่อไปนี้
from tkinter import Tk, Label, Text, Entry, END
# Create the main window
root = tk.Tk()
root.geometry("700x700")
def on_enter(event):
text = entry.get()
lbl.config(text=f"ได้รับข้อมูล: {text}")
entry.delete(0, END)
# Create an Entry widget
entry = Entry(root, font=('Courier 18 bold'))
entry.place(x=180, y=200)
entry.bind("<Return>", on_enter)
# Label Creation
lbl = Label(root, text = "ป้อนข้อมูลและกดปุ่ม Enter บน Keyboard", font=('Courier 18 bold'))
lbl.pack(), lbl.place(x=160, y=150)
root.mainloop()
👉การแสดงข้อมูลแบบตาราง จะมีขั้นตอนการดังต่อไปนี้
from tkinter import Tk, Frame, ttk
# Sample 2D array (rows of data)
data = [
[1, 512, 1],
[2, 623, 0],
[3, 431, 1],
[4, 789, 0],
[5, 250, 1]
]
# Create Tkinter window (same size as before)
root = Tk()
root.title("2D Array in Table")
root.geometry("800x800") # Keep window size the same
# Set Treeview style
style = ttk.Style()
style.configure("Treeview", font=("Courier 15 bold"), rowheight=25) # Reduce row height
style.configure("Treeview.Heading", font=("Courier 15 bold"))
# Create frame for table and scrollbar
frame = Frame(root, width=600, height=200) # Fixed frame size
frame.pack(pady=20)
frame.pack_propagate(False) # Prevent frame from shrinking
# Create Treeview with limited height
columns = ("Id", "Analog Value", "Digital Value")
tree = ttk.Treeview(frame, columns=columns, show="headings", height=3) # Show only 3 rows
# Define column headers
for col in columns:
tree.heading(col, text=col)
tree.column(col, width=180, anchor="center")
tree.pack(side="left", fill="both", expand=True)
# Add scrollbar
scrollbar = ttk.Scrollbar(frame, orient="vertical", command=tree.yview)
tree.configure(yscroll=scrollbar.set)
scrollbar.pack(side="right", fill="y")
# Insert 2D array data into table
for row in data:
tree.insert("", "end", values=row)
root.mainloop()
👉การแสดงผลหรือการรับข้อมูลแบบหลายหน้าจอ จะมีขั้นตอนการดังต่อไปนี้
from tkinter import Tk, Button
def open_secondary_window():
secondary_window = Tk.()
secondary_window.title("Secondary Window")
secondary_window.geometry("500x500+300+300")
button_close = Button(secondary_window,text="Close window",command=secondary_window.destroy)
button_close.place(x=100, y=80)
main_window = Tk()
main_window.geometry("800x800+100+100")
main_window.title("Main Window")
button = Button(main_window,text="Open secondary window",command=open_secondary_window)
button.place(x=100, y=100)
main_window.mainloop()
👉การแสดงผลภาพบนหน้าจอ จะมีขั้นตอนการดังต่อไปนี้
from tkinter import Tk, Label
from PIL import Image, ImageTk
root = Tk()
root.title("Motor_Monitoring")
root.geometry("700x700+300+300")
# Load and display an image
image_path = r"C:\Users\user\Desktop\motor.jpg"
try:
img = Image.open(image_path)
img = img.resize((350, 300)) # Resize image
img = ImageTk.PhotoImage(img)
img_label = Label(root, image=img)
img_label.place(x=200, y=20) # Adjust position
except Exception as e:
print(f"Error loading image: {e}")
# Keep the reference to the image to prevent garbage collection
root.mainloop()