Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีสร้าง GUI ที่อัปเดตอัตโนมัติ (Auto-updating) ด้วย Tkinter

ด้วย Tkinter เราสามารถสร้าง GUI ที่ตั้งค่าให้อัปเดตอัตโนมัติได้ สำหรับวัตถุประสงค์นี้ เราจะสร้างนาฬิกา GUI ที่จะ Refresh อัตโนมัติเมื่อเวลาเปลี่ยน เราจะแสดงนาฬิกาพร้อมวันและ Time Zone

ก่อนอื่น เราจะ import ไลบรารี tkinter ใน Notebook แล้วสร้างฟังก์ชันที่สร้างอินสแตนซ์ของเวลาปัจจุบันและวันโดยใช้ฟังก์ชัน strftime

ตัวอย่าง

# Import the tkinter library
from tkinter import *
import time

# Create an instance of the canvas
win = Tk()

# Select the title of the window
win.title("tutorialspoint.com")

# Define the geometry of the window
win.geometry("600x400")

# Define the clock which
def clock():
    hh = time.strftime("%I")
    mm = time.strftime("%M")
    ss = time.strftime("%S")
    day = time.strftime("%A")
    ap = time.strftime("%p")
    time_zone = time.strftime("%Z")
    
    my_lab.config(text=hh + ":" + mm + ":" + ss)
    my_lab.after(1000, clock)
    my_lab1.config(text=time_zone + " " + day)

# Update the Time
def updateTime():
    my_lab.config(text="New Text")

# Creating the label with text property of the clock
my_lab = Label(win, text="", font=("sans-serif", 56), fg="red")
my_lab.pack(pady=20)

my_lab1 = Label(win, text="", font=("Helvetica", 20), fg="blue")
my_lab1.pack(pady=10)

# Calling the clock function
clock()

# Keep Running the window
win.mainloop()

ผลลัพธ์

การรันโค้ดข้างต้นจะสร้าง GUI Application ที่อัปเดตอัตโนมัติในหน้าต่าง

วิธีสร้าง GUI ที่อัปเดตอัตโนมัติ (Auto-updating) ด้วย Tkinter