如何动态生成 Tkinter 按钮?
在本文中,我们将了解如何在 Tkinter 窗口中动态创建按钮。动态创建按钮意味着通过添加事件对按钮进行自定义和功能性操作。
首先,我们在笔记本中导入 Tkinter 库,然后使用Button函数创建一个实例,该函数采用一些参数,如窗口父级或根级、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 笔记本中运行上述代码,将生成以下输出。

广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP