Can someone explain me how this programm with tkinter works?

Question:

Code:

#library import / set tkinter as tk for shorter calls
from tkinter import *
import tkinter as tk

#create window inc. title and size
root = Tk()
root.title("chessboard with coordinates")
root.geometry('642x570')

#function for coordinates
def coordinates(x,y):
    print(x,y)

for i in range(8):
    if i%2==0:
        for k in range(8):
            if k%2 ==0:
                tk.Button(root, width=10, height=4, bg="black",command=lambda x=i,y=k: coordinates(x,y)).grid(row=i,column=k)
            else:
                tk.Button(root, width=10, height=4, bg="white",command=lambda x=i,y=k: coordinates(x,y)).grid(row=i,column=k)
    else:
        for k in range(8):
            if k%2 ==0:
                tk.Button(root, width=10, height=4, bg="white",command=lambda x=i,y=k: coordinates(x,y)).grid(row=i,column=k)
            else:
                tk.Button(root, width=10, height=4, bg="black",command=lambda x=i,y=k: coordinates(x,y)).grid(row=i,column=k)

root.mainloop()

Can someone explain how these loops work in this code? Would be very grateful, I’m a little confused right now.

Asked By: python_beginner

||

Answers:

Basically, the % is part of basic math and lambda is often called as the anonymous function, because it has no particular name.

So to begin with %:

>>> 5 % 2
1
>>> 8 % 2
0

Look at the example above, %, known as the modulo operator, means it will return the remainder while doing a fraction, in the example while doing 5÷2, it returns the remainder 1. Similarly, while doing 8÷2 it returns the remainder of the fraction, 1. Check here for more

Now about lambda, it’s an easy and very useful function, like a one-liner function. The syntax is lambda <parameters>:<expression>:

lambda x=i,y=k: coordinates(x,y) #without loop it could also be lambda i,k:coordinates(i,k)

Here your assigning i to be a parameter x and k to be a parameter y, and passing it on to the function as arguments. With tkinter it allows you to pass arguments for a function. Here it’s more like your creating a new function(with lambda) that passes the arguments on to the old function created. Check here for more

As I’ve mentioned, without loop it could also be:

lambda i,k:coordinates(i,k)

While your doing a for loop you want to hold the values from the for loop onto the function and that is why you use the first lambda expression and not the second one, if there was no for loop latter one would also work.

This is just for you to understand the basics, to understand better, you will have to google more about it and practice with implementation. This is just what I understood of modulo and lambdas, do correct me if I’m wrong.

Answered By: Delrius Euphoria
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.