我的代码没有任何问题,我只是想看看是否有一个更短的方式来做的
def taskcreator(first,second,third):
first.needs()
second.needs()
third.needs()
如果我可以做这样的事情
def taskcreator(first,second,third):
(first,second,third).needs()
因为我将创建一个'很多更多的对象,我喜欢尽量减少我的代码数量,并使我的代码更有效.预先感谢您的帮助。
import tkinter as tk
from tkinter import ttk
screen = tk.Tk()
class Crop:
def __init__(self,sizename,sizevar,onvar,xvalue,yvalue):
sizevar = tk.StringVar()
self.sizename = sizename
self.sizevar = sizevar
self.onvar = onvar
self.offvalue = 'no'
self.cb = tk.Checkbutton(screen, text=self.sizename, variable=self.sizevar, onvalue=self.onvar, offvalue=self.offvalue)
self.cb.deselect()
self.cb.place(x=xvalue, y=yvalue)
def needs(self):
value = self.sizevar.get()
print(value)
if value != 'no':
print(self.sizename + ' has been checked')
else:
print(self.sizename + ' has not be checked')
def main():
labell = tk.Label(screen, text='Enter Shoe Link').place(x=10, y=20)
first = Crop('UK 2.5', 'twohalf', 'twohalfon', 10, 110)
second = Crop('UK 3', 'three', 'threeon', 200, 110)
third = Crop('UK 3.5', 'threehalf', 'threehalfon', 10, 150)
fourth = Crop('UK 4', 'four', 'fouron', 200, 150)
fith = Crop('UK 4.5', 'fourhalf', 'fourhalfon', 10, 190)
sixth = Crop('UK 5', 'five', 'fiveon', 200, 190)
seventh = Crop('UK 5.5', 'fivehalf', 'fivehalfon', 10, 230)
eigth = Crop('UK 6', 'sixth', 'sixthon', 200, 230)
ninth = Crop('UK 6.5', 'sixthhalf', 'sixthhalfon', 10, 270)
tenth = Crop('UK 7', 'seven', 'sevenon', 200, 270)
newtaskbutton = tk.Button(screen, text='Start', command=lambda: taskcreator(first,second,third))
newtaskbutton.place(x=30,y=10)
def taskcreator(first,second,third):
first.needs()
second.needs()
third.needs()
main()
screen.mainloop()
你可以使用 getattr
和 *args
来实现这一目的。
def taskcreator(*args):
for arg in args:
getattr(arg, 'needs')()
*args
把所有传递到函数中的参数都存储起来,作为一个 tuple
叫做 args
.
getattr
按名称获取对象的an属性--在本例中是指 needs
每个 arg