📜  如何将参数传递给 Tkinter 按钮命令?

📅  最后修改于: 2022-05-13 01:54:58.340000             🧑  作者: Mango

如何将参数传递给 Tkinter 按钮命令?

Tkinter 是Python的标准 GUI 库。 Tkinter 是Python附带的 Tk GUI 工具包的Python接口。它提供了一个健壮且与平台无关的窗口工具包,可供使用此包的Python程序员使用。 Python与 Tkinter 结合使用时,提供了一种创建 GUI 应用程序的快速简便的方法。 Tkinter 为 Tk GUI 工具包提供了一个强大的面向对象的接口。

方法

  • 导入 tkinter 包。
  • 创建一个根窗口。给根窗口一个标题(使用 title())和尺寸(使用几何())。
  • 使用 (Button()) 创建一个按钮。
  • 使用 mainloop() 调用窗口的无限循环。

这两种方法的这些步骤保持不变,唯一需要改变的是如何应用这两种方法。

方法 1:使用 lambda函数

Python3
# importing tkinter
import tkinter as tk
 
# defining function
 
 
def func(args):
    print(args)
 
 
# create root window
root = tk.Tk()
 
# root window title and dimension
root.title("Welcome to GeekForGeeks")
root.geometry("380x400")
 
# creating button
btn = tk.Button(root, text="Press", command=lambda: func("See this worked!"))
btn.pack()
 
# running the main loop
root.mainloop()


Python3
# importing necessary libraries
from functools import partial
import tkinter as tk
 
# defining function
 
 
def function_name(func):
    print(func)
 
 
# creating root window
root = tk.Tk()
 
# root window title and dimension
root.title("Welcome to GeekForGeeks")
root.geometry("380x400")
 
# creating button
btn = tk.Button(root, text="Click Me", command=partial(
    function_name, "Thanks, Geeks for Geeks !!!"))
btn.pack()
 
# running the main loop
root.mainloop()


输出:

使用 lambda

方法 2:使用部分

蟒蛇3

# importing necessary libraries
from functools import partial
import tkinter as tk
 
# defining function
 
 
def function_name(func):
    print(func)
 
 
# creating root window
root = tk.Tk()
 
# root window title and dimension
root.title("Welcome to GeekForGeeks")
root.geometry("380x400")
 
# creating button
btn = tk.Button(root, text="Click Me", command=partial(
    function_name, "Thanks, Geeks for Geeks !!!"))
btn.pack()
 
# running the main loop
root.mainloop()

输出:

使用部分