【问题标题】:Buttons created in loops returning wrong values [duplicate]在返回错误值的循环中创建的按钮[重复]
【发布时间】:2020-08-01 19:11:05
【问题描述】:

我想创建一个带有 1 到 9 按钮的简单计算器。我想在两个循环中执行此操作,以便能够将它们放置在 3x3 正方形中。但是所有按钮都返回相同的值(9),我不知道为什么。任何人都可以帮助我吗? 有一个代码:

from tkinter import *

root = Tk()

e = Entry()
e.grid(row=0, column=0, columnspan=3)


def button_click(num):
    e.insert(0, num)


for i in range(1, 4):
    for j in range(0, 3):
        k = int(((i - 1) * 3) + (j + 1))
        button = Button(root, text=k, padx=25, pady=25, command=lambda: button_click(k))
        button.grid(row=i, column=j)

【问题讨论】:

标签: python tkinter


【解决方案1】:

除了@Roei Duvdevani 回答:您还可以使用 functools.partial:

from functools import partial
from tkinter import *


root = Tk()

e = Entry()
e.grid(row=0, column=0, columnspan=3)


def button_click(num):
    e.insert(0, num)


for i in range(1, 4):
    for j in range(0, 3):
        k = int(((i - 1) * 3) + (j + 1))
        button = Button(root, text=k, padx=25, pady=25, command=partial(button_click, k))
        button.grid(row=i, column=j)

这里有更多关于 functools.partial 的信息:https://www.geeksforgeeks.org/partial-functions-python/

这里是关于您的问题的更多信息:Python Lambda in a loop

【讨论】:

    【解决方案2】:

    这一行几乎是正确的:

    button = Button(root, text=k, padx=25, pady=25, command=lambda: button_click(k))
    

    尝试:

    button = Button(root, text=k, padx=25, pady=25, command=lambda k=k: button_click(k))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-05
      • 1970-01-01
      • 2022-01-24
      • 2022-11-04
      相关资源
      最近更新 更多