【问题标题】:Python Tkinter GUI CalculatorPython Tkinter GUI 计算器
【发布时间】:2016-12-09 17:03:19
【问题描述】:

所以我目前正在制作一个 GUI 计算器,但不确定如何编写代码来执行计算器的操作。现在我已经设置了窗口、输入框和计算器按钮,但目前它们都没有真正做任何事情。

我只是对这些按钮在代码中的表示方式感到困惑,所以我不知道如何编写一个能够读取这些按钮输入并执行加法、减法等的代码块。

这是我目前的代码

class Calculator(Frame):
def __init__(self,master):
    Frame.__init__(self,master)
    self.grid()

    self.dataEnt = Entry(self)
    self.dataEnt.grid(row = 0, column = 1, columnspan = 4)

    labels =[['AC','%','/'],
         ['7','8','9','*'],
         ['4','5','6','-'],
         ['1','2','3','+'],
         ['0','.','=']]
    label = Button(self,relief = RAISED, padx = 10, text = labels[0][0]) #AC
    label.grid(row = 1, column = 0, columnspan = 2)
    label = Button(self,relief = RAISED, padx = 10, text = labels[0][1]) # %
    label.grid(row = 1, column = 3)
    label = Button(self,relief = RAISED, padx = 10, text = labels[0][2]) # /
    label.grid(row = 1, column = 4)
    for r in range(1,4):
        for c in range(4):
            #create label for row r and column c 
            label = Button(self,relief = RAISED,
                          padx = 10,
                          text = labels[r][c]) # 789* 456- 123+ 
            # place label in row r and column c
            label.grid(row = r+1, column = c+1)

    label = Button(self,relief = RAISED, padx = 10, text = labels[4][0]) #0
    label.grid(row = 5, column = 0, columnspan = 2)
    label = Button(self,relief = RAISED, padx = 10, text = labels[4][1]) # .
    label.grid(row = 5, column = 3)
    label = Button(self,relief = RAISED, padx = 10, text = labels[4][2]) # =
    label.grid(row = 5, column = 4)

  def operations(self,num ):

def main():
    root = Tk()
    root.title('Calculator')
    obj = Calculator(root)
    root.mainloop()            

and here is what the calculator looks like so far

我的猜测是,我需要以某种方式将输入读取为字符串,然后让 python 将该字符串评估为数学表达式,但我不知道该怎么做。

感谢您的帮助!

【问题讨论】:

    标签: python user-interface tkinter calculator operator-keyword


    【解决方案1】:

    您可以做的是将所有按钮绑定到一个方法,该方法识别按钮并将字符串附加到列表或评估表达式。然后可以在标签中显示此列表。

    def button_press(self, event):
        widget = event.widget
        text = widget["text"]
        if text != "AC" and text != "=":
            self.operations.append(text)
        elif text == "AC":
            self.operations = []  # Clear the list.
        elif text == "=":
            self.evaluate()
        self.label["text"] = "".join(self.operations)
    
    def evaluate(self):
        try:
            self.operations = [str(eval("".join(self.operations)))]
        except (ArithmeticError, SyntaxError, TypeError, NameError):
            self.operations = ["ERROR"]
    

    此代码不能只是粘贴到您的程序中,它只是为了演示如何解决问题。

    【讨论】:

    • 这很好,泰德。我没想到一个简单的复制和粘贴。感谢您就这个问题提供见解!
    【解决方案2】:

    简单地使用 pyautogui 作为基本的 GUI 计算器

    import math
    import pyautogui
    print( '+ =add |- =subtraction |* =multiplication | / =division |w =remainder of division |i =percentage |s =product of a number by itself \n'
            '|p =prime number |r =square root')
    def p(num):
        for i in range(2, int(num)):
            if int(num) % i == 0:
                return i
        return False
    while True:
        try:
            try:
                #----------------------------------------------------------#
                num=float(pyautogui.prompt('1st','pcalculator'))
                op=pyautogui.prompt('sign','pcalculator')
                if not op == 'p':
                    nun=float(pyautogui.prompt('2nd','pcalculator'))
                if op=='+':
                x=pyautogui.confirm(num+nun,'pcalculator ',buttons=['Ok','Cancel'])
                if x=='Cancel':
                    break
                elif op=='-':
                    x=pyautogui.confirm(num-nun,'pcalculator ',buttons=['Ok','Cancel'])
                    if x=='Cancel':
                    break
                elif op=='*':
                    x=pyautogui.confirm(num*nun,'pcalculator ',buttons=['Ok','Cancel'])
                    if x=='Cancel':
                    break
                elif op=='/':
                    x=pyautogui.confirm(num/nun,'pcalculator ',buttons=['Ok','Cancel'])
                    if x=='Cancel':
                    break
                elif op=='w':
                    x=pyautogui.confirm(num%nun,'pcalculator ',buttons=['Ok','Cancel'])
                    if x=='Cancel':
                    break
                elif op=='i':
                    x=pyautogui.confirm(num/nun*100,'pcalculator ',buttons=['Ok','Cancel'])
                    if x=='Cancel':
                    break
                elif op=='s':
                    x=pyautogui.confirm(num**nun,'pcalculator ',buttons=['Ok','Cancel'])
                    if x=='Cancel':
                    break            
                elif op=='p':
                    if p(num):
                        x=pyautogui.confirm((int(num),'is a composite number'),'pcalculator',buttons=['Ok','Cancel'])
                        if x=='Cancel':
                            break
                    else:
                        x=pyautogui.confirm((int(num),'is a prime number'),'pcalculator ',buttons=['Ok','Cancel'])
                        if x=='Cancel':
                            break
                elif op=='r':
                    x=pyautogui.confirm(math.sqrt(num),'pcalculator ',buttons=['Ok','Cancel'])
                    if x=='Cancel':
                        break
        #-------------------------------------------------------------------#
            except ZeroDivisionError:
                    x=pyautogui.confirm("Error: you can not divide by 0",'pcalculator ',buttons=['Ok','Cancel'])
                    if x=='Cancel':
                        break
        except ValueError:
            x=pyautogui.confirm('Invalid input,use only integers,decimals and symbols.','pcalculator ',buttons=['Ok','Cancel'])
            if x=='Cancel':
                break
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-05
      • 1970-01-01
      • 2016-05-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-25
      • 2021-03-25
      相关资源
      最近更新 更多