如何通过每个循环将 Array 元素分配给 tkinter 按钮? [英] How to assign an Array element to a tkinter button via for each loop?

查看:26
本文介绍了如何通过每个循环将 Array 元素分配给 tkinter 按钮?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个基本的 GUI,我希望能够将数组中的每个项目分配给一个按钮.这些按钮是通过 foreach 循环创建的.

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

以下是我当前的代码.

    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.

GUI 的样子

推荐答案

问题:通过每个循环将一个数组元素分配给一个 tkinter 按钮?

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

如果您想在 单击 上获得 Button['text'],请使用 .bind(... 而不是 command=:

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()

使用 Python 测试:3.5

这篇关于如何通过每个循环将 Array 元素分配给 tkinter 按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆