传递函数引用时传递参数

2024-04-26 02:28:49 发布

您现在位置:Python中文网/ 问答频道 /正文

import tkinter as tk
from tkinter import ttk

def draw_mine_field(x=5, y=3):
    mine_frame = tk.Toplevel(root)
    mine_frame.grid()
    root.withdraw()

    for a in range(x):
        for b in range(y):
            ttk.Button(mine_frame, text='*', width=3 ).grid(column=a, row=b)

root = tk.Tk()
root.title("MS")

startframe = ttk.Frame(root)

ttk.Label(root,text="y").grid(row=1,column=1)
y_entry_box = ttk.Entry(root).grid(row=1,column=2)

ttk.Label(root,text="x").grid(row=1,column=3)
x_entry_box = ttk.Entry(root).grid(row=1,column=4)

ttk.Button(root,text="Start",command=draw_mine_field).grid(row=2,column=1)
ttk.Button(root,text="Quit",command=root.destroy).grid(row=2,column=2)

root.mainloop()

对于这个特殊的例子,可能有一个更简单的方法。基本上,我想知道的是,当在command=draw_mine_field中传递function引用时,如何在不运行函数的情况下传递(x, y)?一般来说,这是怎么工作的?你知道吗


Tags: textimportfieldtkintercolumnbuttonrootframe
1条回答
网友
1楼 · 发布于 2024-04-26 02:28:49

使用functool.partials函数进行闭包。你知道吗

from functools import partial
#...
btn = ttk.Button(root,text="Start",command=partial(draw_mine_field, 5, 3))
btn.grid(row=2,column=1)

有些人会告诉您使用lambda,但这只适用于文本。除非你知道它是怎么工作的,否则我会避免使用lambda。我一直在工作。你知道吗

另外,如果您希望避免将来出现错误,请不要将布局(pack、grid或place)与初始化放在同一行上。你知道吗

相关问题 更多 >