ในบทความนี้ เราจะมาดูวิธีสร้างปุ่มแบบไดนามิกในหน้าต่าง tkinter การสร้างปุ่มแบบไดนามิกหมายถึงการปรับแต่งปุ่มและฟังก์ชันการทำงานโดยเพิ่มเหตุการณ์เข้าไป
ขั้นแรก เราจะนำเข้าไลบรารี tkinter ในสมุดบันทึก จากนั้นเราจะสร้างอินสแตนซ์โดยใช้ ปุ่ม ฟังก์ชันที่รับพารามิเตอร์ เช่น parent หรือ root ของหน้าต่าง textvariable ซึ่งเป็นค่าที่จะกำหนดในแต่ละปุ่มและคำสั่ง
ไวยากรณ์
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 จะสร้างผลลัพธ์ดังต่อไปนี้
