如何在 Python 中使用 tkinter 使用 GUI 编程计算器?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22219993/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:30:41  来源:igfitidea点击:

How can I program a calculator with a GUI using tkinter in Python?

pythonuser-interfacetkintercalculator

提问by Jaydreamer

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

我正在为 GCSE 进行计算,我们受控评估的任务之一是创建一个带有 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.

我可以在没有 GUI 的情况下编写一个简单的计算器,但我不明白如何使用 GUI 完成它。

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.

下面是我从 teampython.wordpress.com 得到的代码,我对它的理解有些模糊,但如果有人能向我解释每个单独的步骤,那将非常有帮助。

 # 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()

采纳答案by MarkyD43

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 defetc.). These contain the various methods by which this code computes it's output.

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

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, Buttonand Entryobjects), 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.

在课程之外,我们有 Tkinter UI 代码。此代码构建您的窗口,您的各种按钮和显示器位于其中。在这种情况下,按钮和文本字段的位置由 'grid' 方法控制。如您所见,每次代码设置一个对象(这里只有Frame,ButtonEntry对象)时,都会有一个关联的.grid(row=x, column=y...etc). 这指定了每个对象在 UI 中的相对位置。例如,使用 grid 方法,您可以通过给第一个对象 row=1, column=0 和第二个 row=2, column=0 等来堆叠两个对象。

The for loop:

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 

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 numpressfunction in Calc(). As you may be able to see, numpressitself updates your display with whatever number you press.

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

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.

此示例中的最后一段代码处理计算器的其余操作,您会注意到,每个代码块也遵循上述创建按钮、分配命令和在 UI 中定位按钮的模式。通过我上面的解释,您可能会看到 中的每个剩余函数都Calc()控制算术运算或 clear 等。

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!).

我意识到这是一堵文字墙,但我希望它有所帮助!如果我一直不清楚或者有什么特别你不明白的地方,让我知道,我会试着解释它(我自己学的时间不长!)。

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

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

Good Luck

祝你好运

回答by gravetii

You need to use a GUI library in Python like PyQt4, wxPythonor Tkinter. The question is too broad to give you anymore details.

您需要使用 Python 中的 GUI 库,如PyQt4wxPythonTkinter。这个问题太广泛了,无法为您提供更多详细信息。

Start with the tutorials that teach you all the basics you need to know about creating GUIs in Python.

从教程开始,这些教程教您在 Python 中创建 GUI 所需的所有基础知识。

PS: Personally, I would suggest you to go with PyQt.

PS:就个人而言,我建议你去PyQt