【问题标题】:Python: Button Command in ArrayPython:数组中的按钮命令
【发布时间】:2021-07-25 08:04:46
【问题描述】:

我正在尝试简化计算器的代码。

我没有为每个按钮编写代码,而是尝试将它们全部放在一个 for 循环中,但事实证明让按钮具有单独的命令是很困难的。

目前代码如下:

from tkinter import *
from functools import partial

win = Tk()

counter = 0
button_text = ("M", "(", ")", "C", "7", "8", "9", "-", "4", "5", "6", "+", "1", "2", "3", "*", "AC", "0", ".", "=")
button_ids = []
label = Label(text="Enter text here", )
label.grid(row=10, column=1, columnspan=4)


def click(n):
    global label
    # get index and ID of button
    print(n)
    button_name = (button_ids[n])
    button_name.configure(text=f"clicked {button_ids[n]}")
    label.config(text=f"{button_ids[n]} clicked")


for r in range(5):
    for c in range(4):
        # create buttons & assign unique arg (i) to run function (change)
        button = Button(win, width=15, text=button_text[counter], command=partial(click, r))
        button.grid(row=r, column=c)
        # add ID to list
        button_ids.append(button)
        # update counter for next button text
        counter += 1

print(button_ids)

win.mainloop()

只有一个 for 循环它可以工作,但添加第二个来创建数组,不会。

如何让每个按钮正常工作/注册?

【问题讨论】:

    标签: python arrays tkinter button command


    【解决方案1】:

    使用command=partial(click, counter),因为函数click需要button_ids[n]

    如果您需要显示按钮名称,可以将button_ids 更改为button_text

    from tkinter import *
    from functools import partial
    
    win = Tk()
    
    counter = 0
    button_text = ("M", "(", ")", "C", "7", "8", "9", "-", "4", "5", "6", "+", "1", "2", "3", "*", "AC", "0", ".", "=")
    button_ids = []
    label = Label(text="Enter text here", )
    label.grid(row=10, column=1, columnspan=4)
    
    
    def click(n):
        global label
        # get index and ID of button
        print(n)
        button_name = (button_ids[n])
        # button_name.configure(text=f"clicked {button_ids[n]}")
        label.config(text=f"{button_text[n]} clicked")
    
    
    for r in range(5):
        for c in range(4):
            print(counter, r, c)
            # create buttons & assign unique arg (i) to run function (change)
            button = Button(win, width=15, text=button_text[counter], command=partial(click, counter))
            button.grid(row=r, column=c)
            # add ID to list
            button_ids.append(button)
            # update counter for next button text
            counter += 1
    
    print(button_ids)
    
    win.mainloop()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-11
      • 2023-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-11
      • 1970-01-01
      • 2013-04-19
      相关资源
      最近更新 更多