错误的传参方式:
import tkinter as tk
from tkinter import messagebox
root = tk.Tk()
root.title("")
root.geometry("500x300")
def function(three):
messagebox.showinfo("","1+2=%d"%three)
button = tk.Button(root,command = function(3))#运行后会直接跳出弹窗
button.pack()
root.mainloop()
方式一:用command = lambda:匿名函数形式传参
import tkinter as tk
from tkinter import messagebox
root = tk.Tk()
root.title("")
root.geometry("500x300")
def function(three):
messagebox.showinfo("","1+2=%d"%three)
button = tk.Button(root,command = lambda:function(3))
button.pack()
root.mainloop()
方法二:使用partial对象传参
import tkinter as tk
from tkinter import messagebox
from functools import partial
root = tk.Tk()
root.title("")
root.geometry("500x300")
def function(three):
messagebox.showinfo("","1+2=%d"%three)
button = tk.Button(root,command = partial(function,3))
button.pack()
root.mainloop()
两种方法各有损益,个人感觉partial方法更像function函数传参,但lambda匿名函数较方便