1 回答

TA貢獻2003條經(jīng)驗 獲得超2個贊
我想你覆蓋了 lambda 函數(shù),它在這個例子中是可變的。我不知道為什么會發(fā)生這種情況(tkinter GUI 也有同樣的問題)但我現(xiàn)在知道一個簡單的解決方法。
如果您定義一個類,它接受一個函數(shù)和一系列參數(shù)和關(guān)鍵字參數(shù),并且只使用這些參數(shù)調(diào)用該函數(shù),您可以將它作為按鈕中的命令引用。使用此解決方法,您可以省略 lambda 并僅調(diào)用帶參數(shù)的函數(shù):
from tkinter import *
import random
class CMD: #Auxilliary function for callbacks using parameters. Syntax: CMD(function, argument1, argument2, ...)
def __init__(s1, func, *args):
s1.func = func
s1.args = args
def __call__(s1, *args):
args = s1.args+args
s1.func(*args)
class gui:
def __init__(self):
win=self.win=Tk()
win.title('Ploters Data!')
def identifier(self,x,y):
print('id',x,y)
def createGraph(self,rows,columns):
for xrow in range(rows+1):
for ycolumn in range(columns+1):
if xrow == 0 or ycolumn == 0:
text = '--'
if xrow == 0:
if ycolumn==5:
text='5'
if ycolumn==10:
text='10'
if ycolumn == 0:
if xrow==5:
text='5'
if xrow==10:
text='10'
if xrow == ycolumn == 0:
text='[]'
pixel = Button(self.win,padx=10,pady=10,text=text,command=CMD(self.identifier,xrow,ycolumn))
pixel.grid(row=xrow,column=ycolumn)
else:
pixel = Button(self.win,padx=10,pady=10,command=CMD(self.identifier,xrow,ycolumn))
pixel.grid(row=xrow,column=ycolumn)
# print(xrow,ycolumn)
self.win.mainloop()
s=gui()
s.createGraph(15,10)
使用這個小改動,您的程序可以正常工作。
添加回答
舉報