Không hiểu đoạn code index= index trong Python

ai có thể giúp mình hiểu được các dòng code này ko nhi ? mình chỉ biết là có chức năng tạo bàn phím và vô hiệu hóa phím khi click, mình ko hiểu chỗ index= index, n=n

def appear(index, letter):
                #clicked(letter)
                buttons[index].config(state="disabled")
           #tạo bàn phím 
            letters=['Q','W','E','R','T','Y','U','I','O','P','A','S','D','F','G','H','J','K','L','Z','X','C','V','B','N','M']
            for index in range(26):                                                                                                                                                             
                n=letters[index]            
                button = Button(window, bg="skyBlue",fg="Black",text=n,font=('Helvetica','20'), width=3, height=1,command=lambda index=index, n=n: appear(index, n))
                if index <9 :
                    button.place(x= 400+(58*int(index)),y= 300)
                elif(index > 8 and index<16):
                    button.place(x= -64+(58*int(index)),y= 358)
                elif(index > 15 and index<21):
                    button.place(x= -412+(58*int(index)),y= 416)
                else:
                    button.place(x= -702+58*int(index),y= 474)

python cần indent code cẩn thận nếu không sẽ chạy lỗi, bạn chỉnh lại code cho chuẩn nhé

1 Like

đoạn này cần break ra thành các phần như sau:
command= Đây là label của argument. Chi tiết tham khảo từ khoá named parameters python

lambda index=index, n=n: appear(index, n)

đây là biểu thức lamda expression trong python. Chi tiết có thể tham khảo với từ khoá lamda expression in python. Đoạn code trên sẽ tương đương với bạn declare 1 function như sau

def example(index=index, n=n):
    appear(index, n)
Button(..., command=example)

đến đây thì index là tên argument. =index là default value (giá trị mặc định) với giá trị mặc định là index. Chi tiết tham khảo từ khoá default argument in python. Tương tự với n

2 Likes
83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?