Вы не можете использовать 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()
с таким интерфейсом.
