简体   繁体   中英

Tkinter in Python, enumerate

I need your help. I want to make a few labels. After clicked, the number on every label should change to a text accordiong to the number. I tried this, but it just changes the text on every label to the last item in the list2. What should I do to make it change accordingly? Numbers and texts are on the same position in both lists.

import tkinter as tk

root = tk.Tk()

list1 = [["one", "two", "three", "four"], ["five", "six", "seven", "eight"],["nine","ten","eleven","twelve"]]
list2 = [["1","2","3","4"], ["5", "6", "7", "8"],["9", "10", "11", "12"]]

def change_label(event):
    for row, rowinlist in enumerate(list2):
        for column, text2 in enumerate(rowinlist):    
            event.widget.configure(text=text2)

for row, rowinlist in enumerate(list1):
    for column, text in enumerate(rowinlist):
        label = tk.Label(text=text, width=15, bd=1, relief="raised")
        label.grid(row=row, column=column)
        label.bind("<1>", change_label)
        x = text

root.mainloop()

It is because you go through all the items in list2 and set the text of event.widget to it, so the final result is the last item of list2 .

You need to save the row and column of each label and use them to set its text:

def change_label(event):
    row, col = event.widget.pos # get the position of clicked label
    event.widget.configure(text=list2[row][col])

for row, rowinlist in enumerate(list1):
    for column, text in enumerate(rowinlist):
        label = tk.Label(text=text, width=15, bd=1, relief="raised")
        label.grid(row=row, column=column)
        label.bind("<1>", change_label)
        label.pos = (row, column) # save the position of label

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM