Подключите кнопки к операциям в калькуляторе, построенном на Python tkinter - PullRequest
0 голосов
/ 28 октября 2018

Нам поручено создать калькулятор в tkinter, и у нас возникают проблемы с очисткой значений из калькулятора, а также с помощью кнопок для выполнения операций: сложение (x, y) вычитание (x, y) деление продукта (x, y) деление (x), у).Буду признателен за любую помощь, чтобы решить мою проблему и улучшить мой код:

from tkinter import*
n1=0
n2=0
operator=''

win=Tk()
frame=Frame(win)
frame.pack()
win.title('Justin Calculator')


txtdisplay=Entry(frame,textvariable=n1,bd=30,insertwidth=1,font=30)
txtdisplay.pack(side=TOP)

def one():
    txtdisplay.insert(END,'1')
def two():
    txtdisplay.insert(END,'2')
def three():
    txtdisplay.insert(END,'3')
def four():
    txtdisplay.insert(END,'4')
def five():
    txtdisplay.insert(END,'5')
def six():
    txtdisplay.insert(END,'6')
def seven():
    txtdisplay.insert(END,'7')
def eight():
    txtdisplay.insert(END,'8')
def nine():
    txtdisplay.insert(END,'9')

def action(arg):
    txtdisplay.insert(END,arg)

def add():
    global n1              
    operator='+'
    n1=float(txtdisplay.get())
    txtdisplay.delete(0,END)

def addition(x,y):
        return x+y
        txtdisplay.insert(END,str(addition)(n1+n2)

Topframe=Frame(win)
Topframe.pack(side=TOP)

num1=Button(Topframe,padx=6, pady=6, bd=5, text='1',command=one,fg='blue')
num1.pack(side=LEFT)

num2=Button(Topframe,padx=6,pady=6,bd=5,text='2',command=two,fg='blue')
num2.pack(side=LEFT)

num3=Button(Topframe,padx=6,pady=6,bd=5,text='3',command=three,fg='blue')
num3.pack(side=LEFT)

centerframe=Frame(win)
centerframe.pack(side=TOP)
num4=Button(centerframe,padx=6,pady=6,bd=5,text='4',command=four,fg='red')
num4.pack(side=LEFT)
num5=Button(centerframe,padx=6,pady=6,bd=5,text='5',command=five,fg='red')
num5.pack(side=LEFT)
num6=Button(centerframe,padx=6,pady=6,bd=5,text='6',command=six,fg='red')
num6.pack(side=LEFT)

centerframe=Frame(win)
centerframe.pack(side=TOP)
num7=Button(centerframe,padx=6,pady=7,bd=5,text='7',command=seven,fg='black')
num7.pack(side=LEFT)
num8=Button(centerframe,padx=6,pady=7,bd=5,text='8',command=eight,fg='black')
num8.pack(side=LEFT)
num9=Button(centerframe,padx=6,pady=7,bd=5,text='9',command=nine,fg='black')
num9.pack(side=LEFT)

centerframe=Frame(win)
centerframe.pack(side=TOP)
subtraction=Button(centerframe,padx=6,pady=7,bd=5,text='-',fg='black')
subtraction.pack(side=LEFT)
num0=Button(centerframe,padx=6,pady=7,bd=5,text='0',fg='black')
num0.pack(side=LEFT)
ExitBtn=Button(centerframe,padx=6,pady=7,bd=5,text='Exit',command=win.destroy,fg='black')
ExitBtn.pack(side=LEFT)

centerframe=Frame(win)
centerframe.pack(side=TOP)
_add=Button(centerframe,padx=6,pady=7,bd=5,text='+',command=add,fg='black')
_add.pack(side=LEFT)
subtraction=Button(centerframe,padx=6,pady=7,bd=5,text='-',fg='black')
subtraction.pack(side=LEFT)
multiplication=Button(centerframe,padx=6,pady=7,bd=5,text='*',fg='black')
multiplication.pack(side=LEFT)
division=Button(centerframe,padx=6,pady=7,bd=5,text='/',fg='black')
division.pack(side=LEFT)
_equal=Button(centerframe,padx=6,pady=7,bd=5,text='=',command=equal,fg='black')
_equal.pack(side=LEFT)

bottomframe=Frame(win)
bottomframe.pack(side=TOP)
clear=Button(bottomframe,padx=6,pady=6,bd=5,text='Clear')
clear.pack(side=LEFT)

win.mainloop()

Ответы [ 2 ]

0 голосов
/ 28 октября 2018

Вы не можете использовать textvariable таким образом:

n1=0
# ...
txtdisplay=Entry(frame,textvariable=n1, ...

Использование textvariable является правильным способом решения этой проблемы, но смешивание доступа к Entry напрямую с использованиемtextvariable, вероятно, не оптимально, поэтому давайте пока бросим textvariable.

Эта программа выглядит так, как будто вы создали интерфейс, не задумываясь заранее о том, как вы собираетесь его запустить.Ниже доработка вашего калькулятора, так что теперь работают "+", "=" и "Очистить".Я также добавил рабочую десятичную точку.Вы должны иметь возможность суммировать числа и добавлять к этим суммам все, что вы хотите.Но вам нужно выяснить, как реализовать оставшиеся операции самостоятельно на основе этих примеров:

import operator
from tkinter import *

def zero():
    txtdisplay.insert(END, '0')
def one():
    txtdisplay.insert(END, '1')
def two():
    txtdisplay.insert(END, '2')
def three():
    txtdisplay.insert(END, '3')
def four():
    txtdisplay.insert(END, '4')
def five():
    txtdisplay.insert(END, '5')
def six():
    txtdisplay.insert(END, '6')
def seven():
    txtdisplay.insert(END, '7')
def eight():
    txtdisplay.insert(END, '8')
def nine():
    txtdisplay.insert(END, '9')

def decimal():
    if '.' not in txtdisplay.get():
        txtdisplay.insert(END, '.')

def add():
    global n1, operation
    operation = operator.add
    n1 = float(txtdisplay.get())
    txtdisplay.delete(0, END)

def equal():
    global operation
    n2 = float(txtdisplay.get())
    txtdisplay.delete(0, END)

    if operation:
        txtdisplay.insert(0, str(operation(n1, n2)))
        operation = None

def clear():
    global n1, operation
    n1 = 0.0
    operation = None
    txtdisplay.delete(0, END)

n1 = 0.0
operation = None

win = Tk()
win.title('StackOverflow Calculator')

options = {'padx':6, 'pady':6, 'bd':5}
sticky = {'sticky': (N, S, E, W)}

frame = Frame(win)
frame.pack()

txtdisplay = Entry(frame, bd=30, insertwidth=1, font=30)
txtdisplay.grid(row=0, columnspan=4)

Button(frame, text='-', fg='black', **options).grid(row=1, column=3, **sticky)
Button(frame, text='*', fg='black', **options).grid(row=1, column=2, **sticky)
Button(frame, text='/', fg='black', **options).grid(row=1, column=1, **sticky)

Button(frame, text='7', command=seven, fg='black', **options).grid(row=2, column=0, **sticky)
Button(frame, text='8', command=eight, fg='black', **options).grid(row=2, column=1, **sticky)
Button(frame, text='9', command=nine, fg='black', **options).grid(row=2, column=2, **sticky)

Button(frame, text='4', command=four, fg='red', **options).grid(row=3, column=0, **sticky)
Button(frame, text='5', command=five, fg='red', **options).grid(row=3, column=1, **sticky)
Button(frame, text='6', command=six, fg='red', **options).grid(row=3, column=2, **sticky)

Button(frame, text='1', command=one, fg='blue', **options).grid(row=4, column=0, **sticky)
Button(frame, text='2', command=two, fg='blue', **options).grid(row=4, column=1, **sticky)
Button(frame, text='3', command=three, fg='blue', **options).grid(row=4, column=2, **sticky)

Button(frame, text='0', command=zero, fg='black', **options).grid(row=5, column=1, **sticky)
Button(frame, text='.', command=decimal, fg='black', **options).grid(row=5, column=2, **sticky)
Button(frame, text='Exit', command=win.destroy, fg='black', **options).grid(row=5, column=0, **sticky)

Button(frame, text='+', command=add, fg='black', **options).grid(row=2, column=3, rowspan=2, **sticky)
Button(frame, text='=', command=equal, fg='black', **options).grid(row=4, column=3, rowspan=2, **sticky)
Button(frame, text='Clear', command=clear, **options).grid(row=1, column=0, **sticky)

win.mainloop()

Наконец, я перестроил ваш интерфейс, используя менеджер grid() в одном кадре вместо pack()и несколько кадров.Я не предполагаю, что именно так должен выглядеть ваш калькулятор, просто лучше использовать grid() с таким интерфейсом.

enter image description here

0 голосов
/ 28 октября 2018

Я исправил все синтаксические ошибки. Я закомментировал вашу ошибку. Есть еще некоторые логические ошибки.

from tkinter import Tk,Frame,Entry,Button

#import tkinter

n1=0
n2=0
operator=''

win=Tk()
frame=Frame(win)
frame.pack()
win.title('Justin Calculator')

END='end'
txtdisplay=Entry(frame,textvariable=n1,bd=30,insertwidth=1,font=30)
#why have you added unnecessary indentation?
txtdisplay.pack(side='top')

def one():
    txtdisplay.insert(END,1)
def two():
    txtdisplay.insert(END,2)
def three():
    txtdisplay.insert(END,3)
def four():
    txtdisplay.insert(END,4)
def five():
    txtdisplay.insert(END,5)
def six():
    txtdisplay.insert(END,6)
def seven():
    txtdisplay.insert(END,7)
def eight():
    txtdisplay.insert(END,8)
def nine():
    txtdisplay.insert(END,9)

def action(arg):
    txtdisplay.insert(END,arg)

def add():
    global n1              
    operator='+'
    n1=float(txtdisplay.get())
    txtdisplay.delete(0,END)

def addition(x,y):

    txtdisplay.insert(END,str(addition)(n1+n2))
    return x+y #the statement after return statement will never get executed


Topframe=Frame(win)
Topframe.pack(side='top')

num1=Button(Topframe,padx=6, pady=6, bd=5, text='1',command=one,fg='blue')
num1.pack(side='left')

num2=Button(Topframe,padx=6,pady=6,bd=5,text='2',command=two,fg='blue')
num2.pack(side='left')

num3=Button(Topframe,padx=6,pady=6,bd=5,text='3',command=three,fg='blue')
num3.pack(side='left')

# side= LEFT or TOP does not work. follw the dicumentation

centerframe=Frame(win)
centerframe.pack(side='top')
num4=Button(centerframe,padx=6,pady=6,bd=5,text='4',command=four,fg='red')
num4.pack(side='left')
num5=Button(centerframe,padx=6,pady=6,bd=5,text='5',command=five,fg='red')
num5.pack(side='left')
num6=Button(centerframe,padx=6,pady=6,bd=5,text='6',command=six,fg='red')
num6.pack(side='left')

centerframe=Frame(win)
centerframe.pack(side='top')
num7=Button(centerframe,padx=6,pady=7,bd=5,text='7',command=seven,fg='black')
num7.pack(side='left')
num8=Button(centerframe,padx=6,pady=7,bd=5,text='8',command=eight,fg='black')
num8.pack(side='left')
num9=Button(centerframe,padx=6,pady=7,bd=5,text='9',command=nine,fg='black')
num9.pack(side='left')

centerframe=Frame(win)
centerframe.pack(side='top')
subtraction=Button(centerframe,padx=6,pady=7,bd=5,text='-',fg='black')
subtraction.pack(side='left')
num0=Button(centerframe,padx=6,pady=7,bd=5,text='0',fg='black')
num0.pack(side='left')
ExitBtn=Button(centerframe,padx=6,pady=7,bd=5,text='Exit',command=win.destroy,fg='black')
ExitBtn.pack(side='left')

centerframe=Frame(win)
centerframe.pack(side='top')
_add=Button(centerframe,padx=6,pady=7,bd=5,text='+',command=add,fg='black')
_add.pack(side='left')
subtraction=Button(centerframe,padx=6,pady=7,bd=5,text='-',fg='black')
subtraction.pack(side='left')
multiplication=Button(centerframe,padx=6,pady=7,bd=5,text='*',fg='black')
multiplication.pack(side='left')
division=Button(centerframe,padx=6,pady=7,bd=5,text='/',fg='black')
division.pack(side='left')
_equal=Button(centerframe,padx=6,pady=7,bd=5,text='=',fg='black')
_equal.pack(side='left')

bottomframe=Frame(win)
bottomframe.pack(side='top')
clear=Button(bottomframe,padx=6,pady=6,bd=5,text='Clear')
clear.pack(side='left')

win.mainloop()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...