Python基础语法笔记 tkinter的简单使用
2023-12-30 23:09:57
语法
物质
动态类型语言,不需要声明类型
数字
类型int float bool
操作 //整除 **幂
字符串
str1 = "Hello python"
str2 = "world"
print(str1 * 3) # 重复输出
print(str1[1]) # 索引访问
print(str1 + " " + str2) # 拼接
print(str1[2:4]) # 字符串切片
print(len(str1)) # 长度
#查找与替换
print(str1.find("python")) # 查找
print(str1.replace("python", "c++")) # 替换
print(str1.split(" ")) # 以关键字划分
print(str2.upper()) # 大小写lower/upper
数组类
列表和元组
list = [1, 2, 3, 4] #列表
tuple = (1, 2, 3, 4) #元组
#列表内容可变,元组不可变
列表的操作
arr = ["apple", "banana", "cherry"]
#添加元素
arr.append("orange") # 在末尾追加元素
arr.insert(1, "pear") # 在第2个位置插入元素
print(arr)
#删除元素
arr.remove("banana") # 删除指定元素
del arr[1] # 删除指定位置的元素
print(arr)
#查找元素
print(arr.index("apple")) # 查找指定元素的索引位置,没找到抛出异常
print("pear" in arr) # 判断指定元素是否在数组中
集合
#集合内不允许重复元素
A = {1, 2, 3}
B = {2, 3, 4}
A & B #{2, 3}
A | B #{1, 2, 3, 4}
A - B #{1}
A ^ B #{1, 4}
A <= B #False
length = len(A);
字典
#就是键值对
person = {'name': 'John Doe', 'age': 30, 'gender': 'Male'}
print(person['name']) # John Doe
类与特殊方法
from filecmp import cmp
class Book:
def __init__(self, title, author, pages):
self.title = title
self.author = author
self.pages = pages
def __str__(self):
return f"{self.title} by {self.author}"
def __repr__(self): # representation
return f"Book('{self.title}', '{self.author}', {self.pages})"
def __len__(self):
return self.pages
def __add__(self, other):
return self.pages + other.pages
def __eq__(self, other):
return (
self.title == other.title
and self.author == other.author
and self.pages == other.pages
)
book1 = Book("The Great Gatsby", "F. Scott Fitzgerald", 180)
book2 = Book("To Kill a Mockingbird", "Harper Lee", 198)
print(book1)
# Output: The Great Gatsby by F. Scott Fitzgerald
print(repr(book1))
# Output: Book('The Great Gatsby', 'F. Scott Fitzgerald', 180)
print(book1 + book2)
# Output: 378
print(book1 == book2)
# Output: False
print(book1 == Book("The Great Gatsby", "F. Scott Fitzgerald", 180))
# Output: True
运动
输入输出
输入
name = input("Please enter your name: ")
#输入
n = int(input())#默认输入尾string类型,可以格式化为int,float
print("Hello, " + name)
sets = set(input('|').split()[1:])#获取以|分割后的第二个至行尾的所有单词
nums = input().split() # 将字符串分割成多个子串
arr = [float(x) for x in nums] # 将每个子串转换成浮点数类型,得到一个浮点数列表
输出
# 普通输出
print("Hello, World!")
# python的每句print自动换行,不需要换行则加end
print("Hello, World!", end="")
print(" Welcome to Python.")
# 格式化输出
name = "John"
age = 30
## 三种格式化
print("My name is {} and I am {} years old.".format(name, age))
print(f"My name is {name} and I am {age} years old.") #Python 3.6引入
print("My name is %s and I am %d years old." % (name, age))
## 控制小数位数
value = 3.1415926
print("The value of pi is {:.2f}.".format(value))
##占位长度以及左右对齐
print("My name is {:10} and I am {:<10} years old.".format(name, age))
'''输出如下
Hello, World!
Hello, World! Welcome to Python.
My name is John and I am 30 years old.
My name is John and I am 30 years old.
My name is John and I am 30 years old.
The value of pi is 3.14.
My name is John and I am 30 years old.
'''
逻辑
- 比较运算,位运算,赋值运算
- 逻辑运算:与(and)、或(or)和非(not)
- 成员运算:在序列(字符串、列表、元组)中检查成员(in 和 not in)
- 身份运算:检查对象是否是同一个(is 和 is not)
控制语句
for i in range(1, 11):
if i == 5:
continue
print(i)
while True:
user_input = input("请输入任意字符,输入'q'退出: ")
if user_input == "q":
break
print("你输入的字符是: " + user_input)
单条件 类似于 c语言中的? :
x = 10
y = 20
max_value = x if x > y else y
print(max_value) # 输出结果为20
函数
#定义计算平方的函数
def square(x):
result = x * x
return result
列表推导式
square_list = [x**2 for x in range(1, 11)]
print(square_list)
#输出如下[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
#统计数组中的重复数字个数
len(set([x for x in nums if x != 0]))
#每个单词的第一个数字
words = ["apple", "banana", "cherry", "dragonfruit", "elderberry", "fig"]
first_letters = {word[0] for word in words}
print(first_letters)
#输出如下{'c', 'b', 'a', 'e', 'd', 'f'}
应用
打包
先安装pip install pyinstaller
然后pyinstaller --onefile -w D:\code\scripts\py\learn.py
打包并包含库文件,并隐藏命令行窗口
虚拟环境
使用虚拟环境打包可以让可执行文件更小
使用python3.6以上自带的venv,在vscode的PS终端中执行以下命令
#创建虚拟环境
python -m venv test_env
#激活环境
.\test_env\Scripts\Activate.ps1#执行不了就先Set-ExecutionPolicy RemoteSigned
#然后安装包
pip list#查看
pip install pandas#安装
#退出环境
deactivate
Tkinter
界面
基于tkinter,需要先安装库pip install ttkbootstrap tkinter
布局
三种布局方式:
pack相对用户来说不需要做过多操作就可以自动元素排列,适合于整体布局
grid布局相对来说有板有眼,适合那种规规矩矩的布局
place布局适合那种对细节要求严丝合缝的场合
pack
widgets.pack(pack_options) 这个是函数原型,pack_options有三个常用属性,分别是expand ,fill,side这三个属性
expand 是否扩展,当它设置为true的时候,它会沾满父组件的空间,当然,这是在其它同级元素布局剩下之后的空间。
fill 是填充的意思,它可以指定填充的方向,比如我们想要一个button或者label占满一行,我们可以就可以设置fill = tk.X (其中tk是tkiner的简写,import tkinter as tk)
side是一侧的意思,比如我们要让两个button并排显示可以一个设置side=tk.LEFT,一个设置为tk.RIGHT
pdx,pdy是用来设置距离左右上下的位置的,有了他们,我们就可以灵活设置组件的布局了
示例
import tkinter as tk
root = tk.Tk()
root.title(u"pack布局演示")
tk.Button(root, text="side:top").pack(side='top')
tk.Button(root, text="side:bottom").pack(side='bottom')
tk.Button(root, text="side:left").pack(side='left')
tk.Button(root, text="side:right").pack(side='right')
root.mainloop()
grid
grid有4个可选参数,分别是row,rowspan,column,columnspan,sticky
row指的是排在第一行
rowspan指的是占有多少行
column指的是排在第几列
columnspan指的是占有几列
sticky粘性,指的就是对齐固定方式,有nswe4个方位,分别是上北下南左西右东(n=nouth,s=south,e=east,w=west)
示例
import tkinter as tk
root = tk.Tk()
root.title(u"grid布局演示")
for row in range(3):
for col in range(4):
text_ = "row=%d, col=%d" % (row, col)
tk.Button(root, text=text_).grid(row=row, column=col)
root.mainloop()
place
坐标布局使用place进行元素的位置放置,它有x,y两参数,可以用来指定距离父组件的左上角的横坐标距离和纵坐标距离。
实战
一个利用tkinter实现逐差法,和作散点图
另外还有更换背景功能
import tkinter as tk
from ttkbootstrap import Style
from tkinter import messagebox
from PIL import Image, ImageTk
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
import os
data = []
def background(window):
def resize_image():
new_width = window.winfo_width()
new_height = window.winfo_height()
resized_image = original_image.resize((new_width, new_height))
new_photo = ImageTk.PhotoImage(resized_image)
background_label.config(image=new_photo)
background_label.image = new_photo
current_path = os.path.realpath(__file__)
current_directory = os.path.dirname(current_path)
jpg_path = os.path.join(current_directory, "background.jpg")
original_image = Image.open(jpg_path)
photo = ImageTk.PhotoImage(original_image)
background_label = tk.Label(window, image=photo)
background_label.place(x=0, y=0, relwidth=1, relheight=1) # 设置Label的相对大小,使其铺满整个窗口
window.bind("<Configure>", lambda event: resize_image())
def create_input(window, text, data_var):
data_frame = tk.Frame(window)
data_label = tk.Label(data_frame, text=text, font=("Arial", 16), width=15)
data_label.pack(side=tk.LEFT)
data_entry = tk.Entry(data_frame, textvariable=data_var)
data_entry.pack(side=tk.LEFT)
# return data_frame
data_frame.pack()
def create_window(text, command):
tk.Button(
root, text=text, font=("Arial", 30), width=10, height=2, command=command
).pack(pady=10)
def full_window(window):
w = window.winfo_screenwidth()
h = window.winfo_screenheight()
window.geometry("%dx%d" % (w, h))
def create_button(window, text, command):
tk.Button(
window, text=text, font=("Arial", 16), width=12, height=1, command=command
).pack(pady=10)
def create_table(num, table_frame):
try:
global data
data.clear()
rows = (num + 9) // 10
cols = min(num, 10)
for i in range(rows):
row = []
if i == rows - 1 and num % 10 != 0:
cols = num % 10
for j in range(cols):
entry = tk.Entry(table_frame, width=6)
entry.grid(row=i, column=j)
row.append(entry)
data.append(row)
except ValueError:
messagebox.showerror("错误", "请输入有效的数据个数!")
def center_window(root, width, height):
screenwidth = root.winfo_screenwidth() # 获取显示屏宽度
screenheight = root.winfo_screenheight() # 获取显示屏高度
size = "%dx%d+%d+%d" % (
width,
height,
(screenwidth - width) / 2,
(screenheight - height) / 2,
) # 设置窗口居中参数
root.geometry(size)
def sub_window_style(window):
# window.title()
center_window(window, 800, 600)
background(window)
def diff():
def calc():
try:
global data
nums = [float(entry.get()) for row in data for entry in row]
n2 = len(nums)
n = n2 // 2
print(n)
result = sum([nums[i + n] - nums[i] for i in range(n)]) / (n * n)
result_text.insert(tk.END, f"逐差法结果为:{result}\n")
except ValueError:
messagebox.showerror("错误", "表格中存在非数字的输入!")
window = tk.Toplevel(root)
sub_window_style(window)
data_N = tk.IntVar()
create_input(window, "数据个数:", data_N)
table_frame = tk.Frame(window)
create_button(
window, text="生成表格", command=lambda: create_table(data_N.get(), table_frame)
)
table_frame.pack()
create_button(window, text="计算", command=calc)
result_text = tk.Text(window, height=30, width=45)
result_text.pack()
def plot():
def gen_table(num, table_frame):
global data
data.clear()
rows = 2
cols = num
for i in range(rows):
row = []
for j in range(cols):
entry = tk.Entry(table_frame, width=6)
entry.grid(row=i, column=j)
row.append(entry)
data.append(row)
def calc():
try:
global data
x = [float(entry.get()) for entry in data[0]]
y = [float(entry.get()) for entry in data[1]]
# 生成折线图
plt.figure(figsize=(6, 4))
plt.plot(x, y, marker="o", label="Data")
plt.xlabel("X")
plt.ylabel("Y")
# plt.title("折线图")
plt.legend()
# 在tkinter窗口中显示折线图
canvas = FigureCanvasTkAgg(plt.gcf(), master=window)
canvas_widget = canvas.get_tk_widget()
canvas_widget.pack(side=tk.BOTTOM, fill=tk.BOTH, expand=True)
except ValueError:
messagebox.showerror("错误", "表格中存在非数字的输入!")
window = tk.Toplevel(root)
sub_window_style(window)
# 创建输入
data_N = tk.IntVar()
create_input(window, "数据个数: ", data_N)
table_frame = tk.Frame(window)
create_button(window, "生成表格", lambda: gen_table(data_N.get(), table_frame))
table_frame.pack()
create_button(window, "生成折线图", lambda: calc())
style = Style(theme="darkly")
root = style.master
root.title("主窗口")
full_window(root)
background(root)
create_window("逐差法", lambda: diff())
create_window("作图", lambda: plot())
root.mainloop()
文章来源:https://blog.csdn.net/killsime/article/details/135310465
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。 如若内容造成侵权/违法违规/事实不符,请联系我的编程经验分享网邮箱:veading@qq.com进行投诉反馈,一经查实,立即删除!