简体   繁体   English

Python 计算器数值问题

[英]Python calculator value Issue

I'm trying to make a calculator with Tkinter in python 3.8.2.我正在尝试在 python 3.8.2 中使用 Tkinter 制作计算器。 I'm trying to make the buttons with a for loop.我正在尝试使用for循环制作按钮。 I made a function that should print the value of the button, but it only prints 3 , that is the last button that the code created.我做了一个 function 应该打印按钮的值,但它只打印3 ,这是代码创建的最后一个按钮。 Can I fix it?我可以修复它吗?

import tkinter as tk

class Calculator:
    def interface(self):
        self.i = tk.Tk()
        self.i.geometry("700x800")
        self.word = ["789","456","123"]
        self.display = tk.Entry(self.i, text = "", width = 107,bg = "#acd", justify = 
                    "right", bd = 30)
        self.display.grid(row = 0)
        self.f = tk.Frame(self.i)
        self.f.grid(row = 1)
        self.rows = 0
        for i in self.word:
            self.col = 0
                for char in i:
                    but = tk.Button(self.f, text = char, command = lambda: 
                        self.writenum(char), height = 8,width = 16)
                    but.grid(row =self.rows, column = self.col)
                    self.col += 1
                self.rows += 1
        self.i.mainloop()

    def writenum(self,arg):
        print(arg)

c = Calculator()
c.interface()

you can use functools.partial to solve your problem.您可以使用functools.partial来解决您的问题。 Instead of using lambda , you can create a callable that will fill appropriate parameter(s) and call different function.除了使用lambda ,您还可以创建一个可调用的对象来填充适当的参数并调用不同的 function。 Here's updated code:这是更新的代码:

import tkinter as tk
from functools import partial


class Calculator:
    def interface(self):
        self.i = tk.Tk()
        self.i.geometry("700x800")
        self.word = ["789", "456", "123"]
        self.display = tk.Entry(
            self.i, text="", width=107, bg="#acd", justify="right", bd=30
        )
        self.display.grid(row=0)
        self.f = tk.Frame(self.i)
        self.f.grid(row=1)
        self.rows = 0
        for i in self.word:
            self.col = 0
            for char in i:
                but = tk.Button(
                    self.f,
                    text=char,
                    command=partial(self.writenum, char),
                    height=8,
                    width=16,
                )
                but.grid(row=self.rows, column=self.col)
                self.col += 1
            self.rows += 1
        self.i.mainloop()

    def writenum(self, arg):
        print(arg)


c = Calculator()
c.interface()

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

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