简体   繁体   English

Python中的Tkinter,枚举

[英]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.我试过这个,但它只是将每个标签上的文本更改为 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 .因为你遍历了list2所有项,并将event.widget的文本设置为它,所以最终结果是list2的最后一项。

You need to save the row and column of each label and use them to set its text:您需要保存每个标签的rowcolumn并使用它们来设置其文本:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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