在我的程序计算器中,如何绑定键。 Tkinter

时间:2019-07-16 14:05:21

标签: python python-3.x tkinter

我想为我的计算器绑定一个键。我想连接钥匙 用计算器中的键盘。但是我不能。

当我在互联网上浏览时,一切都在克拉斯完成了。我必须重写整个程序吗?谢谢你的回答。我是新来的,所以请原谅我的错误。

from tkinter import *
wyrazenie = "
#num
def press(num):
    global wyrazenie
    wyrazenie = wyrazenie + str(num)
    equation.set(wyrazenie)
    #equalpress
def equalpress():
    try:
        global wyrazenie
        total = str(eval(wyrazenie))
        equation.set(total)
        wyrazenie = ""
    except:
        equation.set(" błąd ")
        wyrazenie = ""
#clear
def clear():
    global wyrazenie
    wyrazenie = ""
    equation.set("")
#app
if __name__ == "__main__":
    okno = Tk()
#okno
    okno.configure(background='snow3')
    topFrame = Frame(okno)
    topFrame.grid()
    bottomFrame = Frame(okno)
    bottomFrame.grid()
    okno.title("Kalkulator")
    equation = StringVar()
    wyrazenie_pole = Entry(okno, textvariable=equation)
    wyrazenie_pole.grid(columnspan=4, ipadx=60)

    equation.set('')

#keys
    color_bg = 'deep sky blue' #kolor przycisków
    color_fg = ""
    button1 = Button(okno, text=' 1 ', fg='black', bg=color_bg,
                     command=lambda: press(1), height=1, width=7)
    button1.grid(row=3, column=0)
    if okno.bind('<Button-1>'):

    button2 = Button(okno, text=' 2 ', fg='black', bg=color_bg,
                     command=lambda: press(2), height=1, width=7)
    button2.grid(row=3, column=1)

    button3 = Button(okno, text=' 3 ', fg='black', bg=color_bg,
                     command=lambda: press(3), height=1, width=7)
    button3.grid(row=3, column=2)

    plus = Button(okno, text=' + ', fg='black', bg=color_bg,
                  command=lambda: press("+"), height=1, width=7)
    plus.grid(row=3, column=3)

    minus = Button(okno, text=' - ', fg='black', bg=color_bg,
                   command=lambda: press("-"), height=1, width=7)
    minus.grid(row=4, column=3)

    clear = Button(okno, text='Clear', fg='black', bg=color_bg,
                   command=clear, height=1, width=7)
    clear.grid(row=7, column='1')

    okno.mainloop()

1 个答案:

答案 0 :(得分:0)

def press(num):
    global wyrazenie
    # wyrazenie = wyrazenie + str(num)
    wyrazenie = equation.get() + str(num) # get current text and add last sign pressed
    equation.set(wyrazenie)
    wyrazenie_pole.icursor(len(wyrazenie)) # set cursor at the end

您还可以将重点放在条目上

wyrazenie_pole = Entry(okno, textvariable=equation)
wyrazenie_pole.grid(columnspan=4, ipadx=60)
wyrazenie_pole.focus()