Python GUI 编程(Tkinter)学习笔记

介绍

Python是一种流行的编程语言,可以用来构建各种应用程序。其中GUI编程是Python中比较重要的一部分,而Tkinter则是Python中用于GUI编程的标准库之一。本笔记将介绍如何使用Python Tkinter库构建GUI应用程序。

安装

在Python 2.X版本中,Tkinter已经是Python标准库的一部分。在Python 3.X版本中,需要单独安装Tkinter库。

可以通过以下命令进行安装:

Copy Code
pip install tk

Hello World

下面是一个简单的Tkinter示例程序。它会创建一个窗口并在窗口中显示“Hello, World!”的标签。

pythonCopy Code
import tkinter as tk root = tk.Tk() label = tk.Label(root, text="Hello, World!") label.pack() root.mainloop()

运行上述代码会创建一个窗口,在窗口中心显示“Hello, World!”的标签。

实例 - 计算器

下面我们将使用Tkinter创建一个简单的计算器应用程序。该计算器可以执行加、减、乘、除四个基本运算。

pythonCopy Code
import tkinter as tk class Calculator: def __init__(self, master): self.master = master master.title("Calculator") self.result = 0 self.last_operator = "" self.is_new_num = True self.display = tk.Entry(master, width=30, font=("Helvetica", 20)) self.display.grid(row=0, column=0, columnspan=4, padx=5, pady=5) buttons = [ "7", "8", "9", "/", "4", "5", "6", "*", "1", "2", "3", "-", "0", ".", "=", "+" ] row = 1 col = 0 for button in buttons: command = lambda x=button: self.button_click(x) tk.Button(master, text=button, width=5, height=3, command=command).grid(row=row, column=col, padx=5, pady=5) col += 1 if col > 3: col = 0 row += 1 def button_click(self, key): if key.isdigit() or key == ".": if self.is_new_num == True: self.display.delete(0, tk.END) self.is_new_num = False self.display.insert(tk.END, key) elif key == "+": self.calculate() self.last_operator = "+" elif key == "-": self.calculate() self.last_operator = "-" elif key == "*": self.calculate() self.last_operator = "*" elif key == "/": self.calculate() self.last_operator = "/" elif key == "=": self.calculate() self.last_operator = "" elif key == "C": self.display.delete(0, tk.END) self.result = 0 self.last_operator = "" self.is_new_num = True def calculate(self): if self.last_operator == "+": self.result += float(self.display.get()) elif self.last_operator == "-": self.result -= float(self.display.get()) elif self.last_operator == "*": self.result *= float(self.display.get()) elif self.last_operator == "/": self.result /= float(self.display.get()) else: self.result = float(self.display.get()) self.display.delete(0, tk.END) self.display.insert(tk.END, self.result) self.is_new_num = True root = tk.Tk() calculator = Calculator(root) root.mainloop()

以上代码创建了一个Calculator类,该类继承自Tkinter的Frame类,用于管理整个计算器窗口。计算器的界面由数字、运算符和清除按钮组成,并使用lambda表达式将按钮点击事件关联到button_click()方法上。当用户输入数字或小数点时,button_click()方法会将其显示在计算器的显示屏上;当用户点击运算符或等于号时,button_click()方法会调用calculate()方法执行相应的计算。最后,createWidgets()方法使用grid()方法将所有按钮布局到计算器窗口中。

结语

本文介绍了如何使用Python Tkinter库构建GUI应用程序,并提供了一个简单的计算器示例程序。要成为一名优秀的Python开发者,GUI编程是必须要掌握的技能之一。