Tkinter计算器:按钮输入问题

时间:2019-03-29 22:52:51

标签: python user-interface tkinter lambda calculator

我正在使用Tkinter在班上创建一个计算器。我不知道它是否可以工作,但是我正在使用for循环来创建要按的按钮。例如数字1,2,3以及其他按钮,例如+,/,清除等。

我唯一的问题是,每当您按下该按钮时,尽管显示的内容为“ 1、2、3”,但表达式只带有for循环的最后一个数字。 (在这种情况下,它将是9或10,但是由于我执行了if语句,因此当您单击1、2、3等时,它将显示为4。)

import tkinter
import tkinter as tki
from tkinter import *
#turns the expression into a string
expression = ""

# Function to update expression
# in the text entry box 

def keypress(num): 
    # point out the global expression variable 
    global expression 

    # concatenation of string 
    expression = expression + str(num) 

    # update the expression by using set method 
    equation.set(expression) 


# create a GUI window 
gui = Tk() 
gui.configure(background="light green") 
gui.title("Simple Calculator") 
gui.geometry("265x150") 

equation = StringVar() 
# create the text entry box for 
# showing the expression . 
expression_field = Entry(gui, textvariable=equation) 
#creates a grid for us us to place the widgets.
expression_field.grid(columnspan=5, ipadx=80) 
equation.set('Click the numbers!') 


columnInstance = 0
intNum = 1
columnPlace = 0
rowPlace = 2


#Creates a button
for x in range(10):

        strTextNum = str(intNum)
        #This will be the number that is going to be pressed
        #as well as the number that will be displayed on the
        #widget of the claculator.

        button= Button(gui, text = strTextNum, fg='yellow', bg = 'black',
                command=lambda:keypress(intNum), height = 1, width = 7)
        #Every third time the column occurs, add one to it. Once it reaches 3,
        #go back to 0


        #FIRST ROW(technically second according to python or tkinter)
        #consists of the numbers 1, 2, and 3.
        #If the for loop hasn't gone over 3 yet, then add 1 to the column.
        if columnInstance <= 2:
                #These are the numbers for the position in which we'll
                #place the numbers/widgets

                button.grid(row = 2, column = columnPlace)
                #adds one to the instances as well as the places. 
                columnInstance += 1
                columnPlace += 1
                print(intNum)
                intNum+=1

每次尝试运行for循环时,我都尝试创建一个不同的变量,但这没有用。我还尝试使用数组来更具体地说明我想要在参数中使用的内容,但这没有用。因此,我唯一想到的是,在用于循环查看按钮的情况中,很可能要么必须处理 KeyPress函数,要么是出于某种原因,它只是将按钮重新初始化为当前编号。 (请注意,我已经说过我尝试在循环中创建其他变量,但这些变量仍然无效)

如果是由于第二个原因,那么我想我几乎必须没有for循环。但是,如果没有,请帮忙。

0 个答案:

没有答案