简体   繁体   中英

Python calculator value Issue

I'm trying to make a calculator with Tkinter in python 3.8.2. I'm trying to make the buttons with a for loop. 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. 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. Instead of using lambda , you can create a callable that will fill appropriate parameter(s) and call different 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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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