在 Tkinter 中使用“不同”命令函数创建多个按钮
可以使用**for **循环在 Tkinter 应用程序中初始化按钮。假设我们要创建多个按钮,每个按钮都定义了不同的命令或操作。我们必须首先在 **for ** 循环内初始化按钮。迭代器将返回将为其创建多个按钮实例的对象。
范例
在此示例中,我们将定义一些按钮,这些按钮将具有不同的命令或功能。
#Import the required Libraries
from tkinter import *
from tkinter import ttk
#Create an instance of Tkinter frame
win = Tk()
#Set the geometry of the Tkinter frame
win.geometry("750x250")
#Define a function to update the entry widget
def entry_update(text):
entry.delete(0,END)
entry.insert(0,text)
#Create an Entry Widget
entry= Entry(win, width= 30, bg= "white")
entry.pack(pady=10)
#Create Multiple Buttons with different commands
button_dict={}
option= ["Python", "Java", "Go", "C++"]
for i in option:
def func(x=i):
return entry_update(x)
button_dict[i]=ttk.Button(win, text=i, command= func)
button_dict[i].pack()
win.mainloop()输出
运行以上代码将显示包含一些按钮的窗口。当我们单击某个特定按钮时,它将更新条目小组件中的消息。
现在,单击每个按钮以查看最终输出。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP