如何在Python中使用tkinter使用GUI对计算器进行编程? [英] How can I program a calculator with a GUI using tkinter in Python?

查看:58
本文介绍了如何在Python中使用tkinter使用GUI对计算器进行编程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为GCSE进行计算,受控评估的任务之一是创建带有GUI的计算器。

I'm taking computing for GCSE and one of the tasks for our controlled assessment is to create a calculator with a GUI.

我能够在没有GUI的情况下编写一个简单的计算器,但我不完全了解如何使用GUI来完成。

I'm able to program a simple calculator without a GUI but I don't understand exactly how it can be done with a GUI.

下面是我从teampython.wordpress.com获得的代码,我含糊理解,但是如果有人可以向我解释每个步骤,这将非常有帮助。

Below is a code that I got from teampython.wordpress.com, which I vaguely understand but it would be very helpful if someone could explain each individual step to me.

 # calc.py - a Python calculator
 from tkinter import *


class Calc():
    def __init__(self):
        self.total = 0
        self.current = ""
        self.new_num = True
        self.op_pending = False
        self.op = ""
        self.eq = False


    def num_press(self, num):
        self.eq = False
        temp = text_box.get()
        temp2 = str(num)      
        if self.new_num:
            self.current = temp2
            self.new_num = False
        else:
            if temp2 == '.':
                if temp2 in temp:
                    return
            self.current = temp + temp2
        self.display(self.current)

    def calc_total(self):
        self.eq = True
        self.current = float(self.current)
        if self.op_pending == True:
            self.do_sum()
        else:
            self.total = float(text_box.get())

    def display(self, value):
        text_box.delete(0, END)
        text_box.insert(0, value)

    def do_sum(self):
        if self.op == "add":
            self.total += self.current
        if self.op == "minus":
            self.total -= self.current
        if self.op == "times":
            self.total *= self.current
        if self.op == "divide":
            self.total /= self.current
        self.new_num = True
        self.op_pending = False
        self.display(self.total)

    def operation(self, op): 
        self.current = float(self.current)
        if self.op_pending:
            self.do_sum()
        elif not self.eq:
            self.total = self.current
        self.new_num = True
        self.op_pending = True
        self.op = op
        self.eq = False

    def cancel(self):
        self.eq = False
        self.current = "0"
        self.display(0)
        self.new_num = True

    def all_cancel(self):
        self.cancel()
        self.total = 0

    def sign(self):
        self.eq = False
        self.current = -(float(text_box.get()))
        self.display(self.current)

sum1 = Calc()
root = Tk()
calc = Frame(root)
calc.grid()

root.title("Calculator")
text_box = Entry(calc, justify=RIGHT)
text_box.grid(row = 0, column = 0, columnspan = 3, pady = 5)
text_box.insert(0, "0")

numbers = "789456123"
i = 0
bttn = []
for j in range(1,4):
    for k in range(3):
        bttn.append(Button(calc, text = numbers[i]))
        bttn[i].grid(row = j, column = k, pady = 5)
        bttn[i]["command"] = lambda x = numbers[i]: sum1.num_press(x)
        i += 1

bttn_0 = Button(calc, text = "0")
bttn_0["command"] = lambda: sum1.num_press(0)
bttn_0.grid(row = 4, column = 1, pady = 5)

bttn_div = Button(calc, text = chr(247))
bttn_div["command"] = lambda: sum1.operation("divide")
bttn_div.grid(row = 1, column = 3, pady = 5)

bttn_mult = Button(calc, text = "x")
bttn_mult["command"] = lambda: sum1.operation("times")
bttn_mult.grid(row = 2, column = 3, pady = 5)

minus = Button(calc, text = "-")
minus["command"] = lambda: sum1.operation("minus")
minus.grid(row = 3, column = 3, pady = 5)

point = Button(calc, text = ".")
point["command"] = lambda: sum1.num_press(".")
point.grid(row = 4, column = 0, pady = 5)

add = Button(calc, text = "+")
add["command"] = lambda: sum1.operation("add")
add.grid(row = 4, column = 3, pady = 5)

neg= Button(calc, text = "+/-")
neg["command"] = sum1.sign
neg.grid(row = 5, column = 0, pady = 5)

clear = Button(calc, text = "C")
clear["command"] = sum1.cancel
clear.grid(row = 5, column = 1, pady = 5)

all_clear = Button(calc, text = "AC")
all_clear["command"] = sum1.all_cancel
all_clear.grid(row = 5, column = 2, pady = 5)

equals = Button(calc, text = "=")
equals["command"] = sum1.calc_total
equals.grid(row = 5, column = 3, pady = 5)

root.mainloop()


推荐答案

所以,我会尽我所能解释您给出的代码。 Calc()类包含这段代码的所有功能。该结构意味着主GUI(稍后设置)可以轻松访问每个功能。在 Calc()类中,您可以使用函数(用 def 等表示)。这些包含了此代码计算其输出所用的各种方法。

So, I'll explain the code you've given as best I understand it. The class Calc() contains all the functions for this piece of code. The structure means the main GUI (set up later) can access each function easily. Within the Calc() class, you have your functions (denoted by def etc.). These contain the various methods by which this code computes it's output.

在类之外,我们还有Tkinter UI代码。这段代码将在您的窗口中建立各种按钮和显示。在这种情况下,按钮和文本字段的位置由网格方法控制。如您所见,每次代码设置一个对象(此处仅 Frame Button 条目对象),有一个关联的 .grid(row = x,column = y ... etc)。这指定了UI中每个对象的相对位置。例如,使用网格方法,您可以通过给第一个对象row = 1,column = 0,第二行= 2,column = 0等来堆叠两个对象。

Outside of the class, we have the Tkinter UI code. This code builds your window inside of which your various buttons and displays sit. The positioning of the buttons and text fields in this case is governed by the 'grid' method. As you can see, every time the code sets up an object (here only Frame, Button and Entry objects), there is an associated .grid(row=x, column=y...etc). This specifies the relative positions of each object in the UI. For example, using the grid method you could stack two objects by giving the first object row=1, column=0 and the second row=2, column=0 etc.

for循环:

for j in range(1,4):
    for k in range(3):
        bttn.append(Button(calc, text = numbers[i]))
        bttn[i].grid(row = j, column = k, pady = 5)
        bttn[i]["command"] = lambda x = numbers[i]: sum1.num_press(x)
        i += 1 

可能是UI中唯一无法直接看到您刚刚开始的部分。本质上,它所做的就是自动构建按钮(节省您分别编码每个按钮的时间)。
循环的前两行(希望)显然是在指定范围内的值上循环。在 bttn.append(... 这行下面,在较早建立的calc框架中创建一个按钮对象calc = Frame(root),按钮文本由数字列表(从上面的字面意义 numbers = 789456123 开始),最初,i = 0,所以numbers [i]将返回列表数字中的第一个元素,即numbers [i ]代表i = 1(下次循环)为8,依此类推。 bttn.grid(row = j,column = k,pady = 5)使用前面提到的网格定位方法,但是这里的j和k由循环本身中的值给定(对于行,值为1到4;对于列为0到2-3列;对于列, )。如果您运行代码,则可以看到将放置所有用于输入数字的键盘按钮的位置。此循环的最后一行(除了i + = 1,即向i加1)将为按钮分配命令。命令将调用关联的函数,在本例中为 Calc()中的 numpress 函数。您也许可以看到, numpress 本身会使用您按的任何数字来更新显示。

is probably the only part of the UI that is not straightforward to see if you're just starting out. In essence all it is doing is building buttons automatically (saving you the time to code each one individually). The first two lines in the loop are (hopefully) obviously looping over values in specified ranges. Beneath that the line bttn.append(... creates a button object in the calc frame set up earlier calc = Frame(root), with the button text being given by the list of numbers (literally numbers="789456123" above). Initially, i = 0, so numbers[i] would return the first element in the list numbers, numbers[i] for i=1 (the next time it loops over) would give 8 and so on. The bttn.grid(row = j, column = k, pady = 5) uses the grid positioning method mentioned earlier, but here the j and k are given by the values in the loop itself (values between 1 and 4 in the case of rows, and values between 0 and 2 - 3 columns - in the case of columns). If you run the code, you can see that this will position all the keypad buttons for inputting numbers. The last line in this loop (besides i+=1, i.e add 1 to i), handles assigning the button a command. The command will call an associated function, in this case the numpress function in Calc(). As you may be able to see, numpress itself updates your display with whatever number you press.

最后一个此示例中的代码处理了计算器的其余操作,您将注意到每个操作都遵循上述创建按钮,分配命令并将按钮放置在UI中的模式。通过上面的解释,您也许可以看到 Calc()中的每个其余函数都可以控制算术运算或清除等。

The final block of code in this example handles the remaining operations for the calculator, and you will notice that each also follows the above pattern of creating a button, assigning a command and positioning the button in the UI. With what I've explained above, you may be able to see that each of the remaining functions in Calc() governs an arithmetical operation, or clear etc.

我意识到这是一堵文字墙,但希望对您有所帮助!如果我不清楚或有什么特别不清楚的地方,请告诉我,我会尽力加以解释(我已经很久没学会了!)。

I realise this is a wall of text, but I hope it helps! If I've been unclear or there is anything in particular you don't understand, let me know, I'll try and explain it (I've not long learnt myself!).

您可能会发现此 Tkinter UI指南很有用,我从该指南中学到了很多基础知识。

You might find this Tkinter UI Guide useful, I learnt a lot of the basics from that guide.

祝你好运

这篇关于如何在Python中使用tkinter使用GUI对计算器进行编程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆