2017-03-15 102 views
0
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中傳遞參數時,如何在不運行該函數的情況下通過(x, y)?總的來說,這是如何工作的?通過函數參考時傳遞參數

+1

x和y來自哪裏,如果不是默認值? –

+0

您不能將值傳遞給函數而不運行它。在這個設計中你可以做的是設置一些全局變量,並且使用這些函數而不是參數,但這並不完全是優雅的設計。通常在GUI中,您需要將x和y值輸入到輸入窗口小部件(文本框或旋轉框)中,並從中讀取繪圖函數。 –

回答

2

使用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。部分時間工作。另外,如果您希望在將來避免錯誤,請不要將佈局(包,網格或位置)與初始化位於同一行。

+0

像這樣使用'partial'只在參數的值在其創建的Button按鈕時已知。如果是這種情況,OP可能會使用默認參數值(如其問題中的代碼所示)。 – martineau