Using Lambda and tuples to send to Multiple Functi

2019-02-28 01:54发布

问题:

column1 = [
('H', 'Hydrogen', 'Atomic # = 1\nAtomic Weight =1.01\nState = Gas\nCategory = Alkali Metals'),
('Li', 'Lithium', 'Atomic # = 3\nAtomic Weight = 6.94\nState = Solid\nCategory = Alkali Metals'),
('Na', 'Sodium', 'Atomic # = 11\nAtomic Weight = 22.99\nState = Soild\nCategory = Alkali Metals'),
('K', 'Potassium', 'Atomic # = 19\nAtomic Weight = 39.10\nState = Solid\nCategory = Alkali Metals'),
('Rb', 'Rubidium', 'Atomic # = 37\nAtomic Weight = 85.47\nState = Solid\nCategory = Alkali Metals'),
('Cs', 'Cesium', 'Atomic # = 55\nAtomic Weight = 132.91\nState = Solid\nCategory = ALkali Metals'),
('Fr', 'Francium', 'Atomic # = 87\nAtomic Weight = 223.00\nState = Solid\nCategory = Alkali Metals')]
#create all buttons with a loop
r = 1
c = 0
for b in column1:
    tk.Button(self,text=b[0],width=5,height=2, bg="grey",command=lambda text=b[1]:self.name(text)).grid(row=r,column=c)
    r += 1
    if r > 7:
        r = 1
        c += 1

...

def name(self, text):
    self.topLabel.config(text=text)

def info(self, text):
    self.infoLine.config(text=text)

I want to use these tuples and send the 2nd position (the element name) to the name() function(which i currently have and works), and the 3rd position (all of the element information) to the info() function, and print them both out, but they will be in different locations. No matter what I try, I cant seem to be able to do so. Can you send multiple things using tuples to different functions?

回答1:

On the line that you create your button, you can accomplish this either with a (stupid) lambda trick:

tk.Button(self,text=b[0],width=5,height=2, bg="grey", 
command=lambda text=b:[self.name(text[1]), self.info(text[2])] ).grid(row=r,column=c)

or define a separate function that calls both:

tk.Button(self,text=b[0],width=5,height=2, bg="grey", 
command=lambda text=b:self.call_both(text)).grid(row=r,column=c)

def call_both(self, line):
    self.name(line[1])
    self.info(line[2])