How to assign an Array element to a tkinter button via for each loop?

99封情书 提交于 2020-01-30 11:09:46

问题


I am building a basic GUI and I want to be able to assign each item in my array to a button. The buttons are created via a foreach loop.

I am trying to make the button display its respective letter on click.

Originally, I thought simply adding a "command" attribute to the button would create the association I needed. This only prints a list of all of letters. I don't want it print every letter, but simply print whichever letter of the button I click

Below is my current code.

    alphabet = ["A", "B", "C", "D" , "E" , "F" , "G" , "H" , "I" , "J" , "K" , "L" , "M" , "N", "O" , "P" , "Q" , "R" , "S" , "T" , "U" , "V" , "W" , "X" , "Y" , "Z", " ", " "]
    count = 0

    for r in range(7):
        for c in range(4):
            tk.Button(self.searchFrame, text=alphabet[count], height='4', width='8', bg='white', fg='deep sky blue',
            font=("Helvetica", 18),command=self.listitems(alphabet[count])).grid(row=r,column=c)
            count += 1

def listitems(self, letter):
    print(letter)

I am expecting each button to display their respective letter on click.

This is what the GUI looks like


回答1:


Question: assign an Array element to a tkinter button via for each loop?

If you want to get the Button['text'] on click, use .bind(<Button-1>... instead of command=:

import tkinter as tk

class App(tk.Tk):
    def __init__(self):
        super().__init__()

        for r in range(1, 8):
            for c in range(1, 5):
                btn = tk.Button(self, text=chr((r*4)+c+60),
                                height='1', width='1',
                                bg='white', fg='deep sky blue', font=("Helvetica", 18))
                btn.grid(row=r,column=c)
                btn.bind('<Button-1>', self.listitems)

    def listitems(self, event):
        print(event.widget['text'])

if __name__ == "__main__":
    App().mainloop()

Tested with Python: 3.5



来源:https://stackoverflow.com/questions/55734067/how-to-assign-an-array-element-to-a-tkinter-button-via-for-each-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!