Gopakumar PB
Gopakumar PB

Reputation: 29

Separate fuction for each button

Trying to create a python program in tkinter to mark attendance of persons engaged in a special duty. By clicking the button containing their name the figure right to their name is incremented by 1. While i created the function when any button is placed all figures are got incremented. And the attempt finally reached here.

from tkinter import *
staff=['GEORGE ', 'JAMES ', 'THOMAS', 'MATHEW',
       'CLETUSCRUZ', 'FREDY', 'PAUL', 'MEGANI', 'BILL',
       'JULIA ']


def factory(number):
   def f():
        number.set(number.get()+1)
   return f    
functions =[]
for i in range(10):
    functions.append(factory(i))
for i in functions:
    f()
window = Tk()
window.title(" Duty List")
window.geometry('320x900')
number = IntVar()


row_value =3
for i in staff:
    ibutton = Button(window, text= i, command=clicked)
    ibutton.grid(column=1, row=row_value)
    ilabel = Label(window, textvariable=number)
    ilabel.grid(column=2,row=row_value)
    
    row_value+=1
window.mainloop()`

Upvotes: 0

Views: 43

Answers (1)

Derek
Derek

Reputation: 2234

Factory now creates a unique IntVar for each individual.

link connects button press to onclick for processing IntVar

I've used columnconfigure to push the numbers to the right hand side of window

import tkinter as tk

staff=["GEORGE ", "JAMES ", "THOMAS", "MATHEW",
       "CLETUSCRUZ", "FREDY", "PAUL", "MEGANI", "BILL",
       "JULIA "]

window = tk.Tk()
window.title(" Duty List")
window.columnconfigure(1, weight = 1)

def factory(n):
    return tk.IntVar(value = n)

def onclick(a):
    b = a.get()+1
    a.set(b)

def link(a, b):
    return lambda: a(b)
    
for i,n in enumerate(staff):
    b = factory(0)
    a = tk.Button(window, text= n, bd = 1)
    a.grid(column = 0, row = i, sticky = tk.NW, padx = 4, pady = 4)
    a["command"] = link(onclick, b)

    l = tk.Label(window, text = "", textvariable = b, anchor = tk.NW)
    l.grid(column = 1, row = i, sticky = tk.NE, padx = 4, pady = 4)

window.geometry("200x319")
window.resizable(False, False)
window.mainloop()

Upvotes: 1

Related Questions