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

วิธีสร้าง Tkinter Buttons แบบไดนามิก (Dynamically)

ในบทความนี้ เราจะดูวิธีสร้างปุ่มแบบไดนามิกในหน้าต่าง Tkinter การสร้างปุ่มแบบไดนามิกหมายถึงการปรับแต็บปุ่มและฟังก์ชันการทำงานโดยการเพิ่ม Event ให้กับปุ่ม

ก่อนอื่น เราจะ import ไลบรารี tkinter ใน Notebook แล้วสร้างอินสแตนซ์โดยใช้ฟังก์ชัน Button ซึ่งรับพารามิเตอร์ เช่น Parent หรือ Root ของหน้าต่าง Textvariable ซึ่งเป็นค่าที่จะกำหนดในแต่ละปุ่ม และ Command

รูปแบบ (Syntax)

Button(parent, textvariable, command)

ตัวอย่าง

from tkinter import *
import tkinter as tk

# create an instance of tkinter
win = tk.Tk()

# Define the size of the window
win.geometry("700x200")

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

# number of buttons
n = 10

# Defining the row and column
i = 3

# Iterating over the numbers till n and creating the button
for j in range(n):
    mybutton = Button(win, text=j)
    mybutton.grid(row=i, column=j)

# Keep the window open
win.mainloop()

ผลลัพธ์

การรันโค้ดข้างต้นใน Tkinter Notebook จะสร้างผลลัพธ์ดังนี้:

วิธีสร้าง Tkinter Buttons แบบไดนามิก (Dynamically)