Python 四天速成

以下为我在某网站这四天入门python的代码及其注释,共1500多行,po到csdn以防文件丢失,可以使用Ctrl+F来快速查找。

这里的python注释肯定是不全的,因为我懒(bushi),能有起码的计算机语言知识就能阅读。

肯定是不全的,但可以见证一下python的学习。

下面有很多编程示例十分有趣,如文本编辑器,时钟,贪吃蛇等。

封面图即下面所用的”learn.png“

# print("hello python")
# import random
# import time
# 字符串用双引号或者单引号引起
# first_name = "Bro"
# last_name = "Code"
# full_name = first_name + last_name
# print("hello" + full_name)

# age = 21
# age = age + 1
# print(age)
# print(type(age))
# 其他类型和字符串合并需要先转型成str
# print("your age is"+str(age))


# 布尔值首字母要大写
# human = False
# print(human)
# print(type(human))


# 可以连等,可以一次性赋值
# name = "bro"
# age = 21
# attractive = True
# name, age, attractive = "hi", 22, False
# a = b = c = 20
# print(a,b,c)

# name = "Bro Code"
# print(len(name))
# print(name.find("o"))
# print(name.rfind("o"))
# print(name.upper())
# print(name.count("o"))
# 可以用*多次
# name = name*3
# print(name)


# 弱类型可以随意转换
# f = 12.32
# print(type(f))
# f = str(f)
# print(type(f))


# input接受的是str需要改成其他类型操作
# name = input("your name?:")
# print(name)
# age = int(input("your age?:"))
# age = age + 1
# print(age)

# import math
# pi = 3.14
# print(round(3.14))
# print(math.cos(pi))
# print(math.sqrt(pi))


# [start:end:step]step默认为1,start默认为0,end默认为len-1
# site = "https://www.baidu.com"
# site = site[0::2]
# site = site[::-1]  # 反转
# print(site)

# web = "https://www.baidu.com"
# company_slice = slice(8+4, -4)  # 相当于创造了一个切片的规则
# print(web[company_slice])


# if-else or if-elif-else
# 注意判断的顺序
# age = int(input("your age:"))
# if age > 18:
#     print("you're a adult")
# else:
#     print("you're a child")


# 与或非 and or not
# temp = float(input("your temperature:"))
# if temp >= 0 and temp <= 30:
#     print("good day")
# elif temp < 0 or temp > 30:
#     print("bad day")


# while-loop
# while True:
#     print("a")

# for-loop
# for i in "asda":
#     print(i)

# nested-loop
# rows = int(input('rows:'))
# columns = int(input('columns:'))
# img = input("img:")
# for i in range(rows):
#     for j in range(columns):
#         print(img, end="")
#     print()


# how to break a loop
# continue,break,pass.
# pass acts a placeholder
# continue is used to skip
# break is for terminating

# list
# food = ["pizza"]
# food[0] = "banana"
# food.append("asd")
# food.extend("asd")
# print(food)
# new_food = ["zongzi", "chicken"]
# food.extend(new_food)
# for f in food:
#     print(f)

# drinks = ["tea", "coffee", "soda"]
# dinner = ["pizza", "hamburger", "hotdog"]
# dessert = ["cake", "ice cream"]
# food = []
# food.append(drinks)
# food.append(dinner)
# food.append(dessert)
# print(food)
# for i in food:
#     print(i)
#     for f in i:
#         print(f, end=",")
#     print()


# 元组,不可改变
# student = ("bro", 21)
# a = student.count("bro")
# print(a)

# 集合
# s = {"1", 2, 3}
# s = s.union({1, 2})
# print(s)

# 字典
# d = {'name': "bro", 'age': 18}
# print(d)
# 使用get比直接【】要安全,不会报错
# print(d.keys())
# print(d.values())
# for k in d.keys():
#     print(d.get(k))
# d.update({'add': 'china'})
# print(d)

# function
# def hello(name=""):
#     print("hello!"+str(name)
# hello()
# 有默认的放后面,*放倒数第二,**放倒数第一
# 注意* 是元组
# def function(v1,v2=?,*v3,**v4):
#   pass

# def multiply(a: int = 1, b: int = 1) -> list:
#     return a * b
# aa = multiply("1", 3)
# print(aa)


# nested functions calls
# 嵌套函数调用
# print(round(float(input("number"))))


# 注意变量是全局还是局部变量
# 首先寻找局部,若局部没有则寻找全局变量
# name = 'global'
# def display_name():
#     # name = 'local'
#     print(name)
# print(name)
# display_name()


# str formate
# animal = "cat"
# food = "mouse"
# print(f"the {animal} ate a {food}")
# print("the {} ate a {}".format(animal, food))
# print("the {1} ate a {0}".format(food, animal))
#
# num = 314159
# print("the num is {:.3f}".format(num))
# print("the num is {:,}".format(num))
# print("the num is {:b}".format(num))

# import random
#
# x = random.randint(1, 6)
# print(x)
# y = random.random()
# print(y)
# s = [1, 2, 3, 4, 5, 'a']
# ss = random.choice(s)
# print(ss)
# ss = random.choices(s)
# print(ss)
# random.shuffle(s)
# print(s)


# try
# try:
#     a = int(input())
#     b = int(input())
#     print(a/b)
# except ZeroDivisionError as e:
#     print(e)
#     print("you idiot")
# except Exception as e:
#     print(e)
#     print("something went wrong :(")
# finally:
#     print("Done")


# file
# import os
#
# path = './learn.txt'
# if os.path.exists(path):
#     print("exist")
#     if os.path.isfile(path):
#         print("its a file")
#         print("=" * 15)
#         # 上下文管理器
#         with open(path) as f:
#             s = f.read()
#             print(s)
#     elif os.path.isdir(path):
#         print("its a dir")
# else:
#     print("oh no!")


# 复制文件
# import shutil
# shutil.copy("./learn.txt", './new.txt')

# 剪贴
# import os
# source = './learn.txt'
# des = './new.txt'
# try:
#     p = os.path
#     if p.exists(des):
#         print("already exist")
#     else:
#         os.replace(source, des)
#         print("done")
#
# except FileNotFoundError as e:
#     print(e)


# 删除
# import os
# import shutil
# path = 'learn.txt'
# try:
#     os.remove(path)
#     # shutil.rmtree(path)  # 删除一个文件夹及其下的文件
#     print("DOne")
# except OSError:  # 不可以删除
#     print("no empty")
# except PermissionError:  # 没权限
#     print("no right")
# except FileNotFoundError:  # 没找到文件
#     print("no file")


# 石头剪刀布
# import random
# guess = input('your choice:')
# win = {'rock': 'paper', 'paper': 'scissors', 'scissor': 'rock'}
# s = random.choice(['rock', 'paper', 'scissor'])
# print(s)
# if win.get(s) == guess:
#     print('you win')
# else:
#     print('you lose')


# import message
# # message module
# # def hello(name=""):
# #     print("hello"+name)
# #
# #
# # def bye(name=""):
# #     print("bye"+name)
# message.hello()
# message.bye()

# from message import hello
# hello()
# bye()  # from message import bye
# help("modules")
# 官方网站 docs.python.org/3/py-modindex.html


# 类变量直接初始,通过类名来统一修改,通过对象则只修改本对象的值
# class Car:
#     wheels = 4
#
#     def __init__(self, color):
#         self.color = color
#
#     def drive(self):
#         print("driving")
#
#
# c = Car("red")
# c.drive()
# Car.wheels = 3
# c.wheels = 4
# print(c.wheels, id(c))
# cc = Car("black")
# print(cc.wheels, id(cc))


# 类相关以及单层继承或单继承
# 继承的类可以重写
# class Animal:
#     alive = True
#
#     def __init__(self, race, color, name, gender):
#         self.race = race
#         self.color = color
#         self.name = name
#         self.gender = gender
#
#     def eat(self):
#         print(self.name, "eating")
#
#     def move(self):
#         print(self.name, "moving")
#
#     def die(self):
#         self.alive = False
#
#     def __str__(self):
#         print("", self.race, self.name, self.color)
#
#
# class Dog(Animal):
#     def __init__(self, color, name, gender):
#         super(Dog, self).__init__("dog", color, name, gender)
#
#     def move(self):
#         print(self.name, "running")
#
#
# class Fish(Animal):
#     def __init__(self, color, name, gender):
#         super(Fish, self).__init__("fish", color, name, gender)
#
#     def move(self):
#         print(self.name, "swimming")
#
#
# d = Dog("black", "wof", "m")
# f = Fish("transparent", "faith", "f")
# print(d.color)
# print(f.race)

# 多层继承
# class Organism:
#     alive = True
# class Animal(Organism):
#     def eat(self):
#         print("eating")
# class Dog(Animal):
#     def bark(self):
#         print("barking")
# d = Dog()
# print(d.alive)
# d.eat()
# d.bark()


# 多继承
# class Prey:
#     def flee(self):
#         print("fleeing")
#
# class Predator:
#     def hunt(self):
#         print("hunting")
#
# class Fish(Prey, Predator):
#     pass
# f = Fish()
# f.hunt()
# f.flee()

# 通过类里面返回self来实现链式调用
# class Car:
#     def drive(self):
#         print("driving")
#         return self
#     def start(self):
#         print("start")
#         return self
# c = Car()
# c.start().drive()


# 抽象类和抽象方法
# from abc import ABC, abstractmethod
# class Vehicle(ABC):
#     @abstractmethod
#     def go(self):
#         pass
# class Car(Vehicle):
#     def go(self):
#         print("you drive the car")
# class Bike(Vehicle):
#     def go(self):
#         print("you ride the bike")
# c = Car()
# b = Bike()
# c.go()
# b.go()


# 对象作为函数参数
# python并不会去检查对象的类型
# class Car:
#     color = None
#     def __init__(self, color):
#         if self.color is None:
#             self.color = color
# def change_color(car:Car, color):
#     car.color = color
# c = Car("black")
# print(c.color)
# change_color(c, "blue")
# print(c.color)


# :=可以放在语句中赋值给变量
# foods = list()
# while (food := input("your food:")) != "q":
#     foods.append(food)
# # while (food = input("your food:")) != "q":  # 错误
# #     foods.append(food)
# print(foods)


# 可以用其他变量指向函数名,函数名是指向内存地址的一个变量
# def hello():
#     print("hello")
# a = hello
# a()
# say = print
# say("hi")


# 传入一个函数来调用
# def loud(text:str):
#     return text.upper()
# def quiet(text:str):
#     return text.lower()
# def hello(func):
#     text = func("hELLo")
#     print(text)
# hello(loud)
# hello(quiet)


# def divisor(x):
#     def dividend(y):
#         return y/x
#     return dividend
# divide = divisor(2)  # 把dividend传给divide
# d = divide(10)  # 把dividend的结果传给d
# print(d)


# lambda表达式
# double = lambda x:x*2
# print(double(2))


# s = ['asd', 'qwe', 'wqe', 'sdfs', 'wref']
# s.sort(reverse=True)
# print(s)
# s = ('asd', 'qwe', 'wqe', 'sdfs', 'wref')
# s_s = sorted(s)
# print(s_s)
# lambda用在一些像sort之类的不需要再次使用的地方
# s = [
#     ('asd', 'fa', 40),
#     ('asg', 'asd', 43),
#     ('fgs', 'affg', 33),
#     ('dfgd', 'dasd', 21)
# ]
# s.sort(key=lambda x: x[2], reverse=True)
# print(s)


# map(function,iterable),一一将function作用到iterable对象中
# s = [
#     ('asd', 'fa', 40),
#     ('asg', 'asd', 43),
#     ('fgs', 'affg', 33),
#     ('dfgd', 'dasd', 21)
# ]
# to_euros = lambda d: (d[0], d[2]*0.34)
# ss = list(map(to_euros, s))
# print(ss)


# filter(function,iterable)
# function返回True或者False,保留True对应的迭代对象
# s = [
#     ('asd', 40),
#     ('asg', 43),
#     ('fgs', 33),
#     ('dfgd', 21)
# ]
# age = lambda x: x[1] % 2 != 0
# ss = list(filter(age, s))
# print(ss)


# reduce(function,iterable)
# function有两个参数,a*b
# (a*b)*c一次类推,* 为演示用运算或操作
# from functools import *
# a = lambda x, y: x * y
# n = [1, 2, 3, 4, 5, 6]
# print(reduce(a, n))


# 列表表达式
# squares = [i * i for i in range(1, 10)]
# n = [123, 23, 534, 5, 234, 756, 7, 34, 3, 65, 56, 87, 763, 54, 35, 43, 54, 34]
# # n = list(filter(lambda x: x % 2 == 0, n))
# n = [i for i in n if i % 2 == 0]
# print(n)
# print(squares)


# 字典表达式
# citiesInF = {'new york': 32, 'boston': 75, 'los angeles': 100, 'chicago': 50}
# citiesInC = {key: round((value-32)*5/9, 2) for key, value in citiesInF.items()}
# print(citiesInC)


# zip(*iterable)
# 一一对应,成一个元组
# uname = ['qwe', 'qsad', 'asdg', 'gdfg']
# upwd = ['adssssss', 'gfdfgdgd', 'asdfggnf', 'jkjfocsd']
# date = ['213-234-23','234-4346-76', '34-879-396', '5668-345']
# user = zip(uname, upwd, date)
# print(type(user))
# for u in user:
#     print(u)


# __name__为main当且仅当当前py文件为程序入口模块
# if __name__ == '__main__'可用于测试模块,当被引用时,此代码块下的代码不会运行


# time module
# import time
# print(time.ctime(0))
# print(time.time())  # current_second from that
# print(time.ctime(time.time()))
# print(time.localtime())
# print(time.strftime("%Y-%m-%d %H:%M:%S %j", time.localtime()))
# print(time.gmtime())  # 标准时间

# timestr = '2023-1-7 18:00'
# t = time.strptime(timestr, "%Y-%m-%d %H:%M")  # 将字符串转换成struct_time
# print(t)
# (year,month,day,hours,minutes,secs,day of the week,day of the year,dst)
# timetuple = (2023, 1, 7, 18, 0, 0, 5, 0, 0)
# t = time.asctime(timetuple)  # 将tuple转换成字符串
# print(t)


# threading用法
# import threading
# import time
#
# def eat():
#     time.sleep(3)
#     print("eating")
# def drink():
#     time.sleep(4)
#     print("drinking")
# def study():
#     time.sleep(5)
#     print("studying")
#
# x = threading.Thread(target=eat, args=())
# x.start()
# y = threading.Thread(target=drink, args=())
# y.start()
# z = threading.Thread(target=study, args=())
# z.start()
# # 加到主线程中
# x.join()
# y.join()
# z.join()
# print(threading.active_count())
# print(threading.enumerate())
# print(time.perf_counter())


# daemon
# 通过对daemon设置使其在主线程退出的时候也能退出
# import threading
# import time
# def timer():
#     count = 0
#     while True:
#         time.sleep(1)
#         count += 1
#         print("waiting for ", count, " second")
# x = threading.Thread(target=timer, daemon=True)
# # x.setDaemon(True)
# x.start()
# ans = input("your answer:")


# multiprocessing
# from multiprocessing import Process, cpu_count
# import time
# def counter(num):
#     count = 0;
#     while count < num:
#         count += 1
# def main():
#     print(cpu_count())  # 线程数
#     a = Process(target=counter, args=(250000000,))
#     b = Process(target=counter, args=(250000000,))
#     c = Process(target=counter, args=(250000000,))
#     d = Process(target=counter, args=(250000000,))
#     a.start()
#     b.start()
#     c.start()
#     d.start()
#     a.join()
#     b.join()
#     c.join()
#     d.join()
#
#     print("finished in:",time.perf_counter())
#
# if __name__ == '__main__':
#     main()


# GUI windows
# from tkinter import *
# window = Tk()  # 实例化一个窗口
# window.geometry("400x900")
# window.title("my title")
# # icon = PhotoImage(file="")
# # window.iconphoto(True, icon)  # 设置icon
# window.config(background="#3fc")  # 设置背景
# # photo = PhotoImage(file="learn.png")
# lable = Label(window,
#               text="hello tk",
#               font=('Arial', 20, 'bold'),
#               fg="white",
#               bg="lightgreen",
#               relief=RAISED,
#               bd=10,
#               padx=40,
#               pady=30,
#               # image=photo,
#               # compound='bottom')
#               )
# # lable.place(x=0, y=0)  # 设置lable的位置
# lable.pack()  # 默认居中
# window.mainloop()


# button
# from tkinter import *
# count = 0
# def click():
#     global count
#     count += 1
#     print("clicked",count)
#
# window = Tk()
# # photo = PhotoImage(file="learn.png")
# button = Button(window,
#                 text="click me!",
#                 command=click,
#                 font=('Comic Sans', 30, 'bold'),
#                 fg='green',
#                 bg='white',
#                 activeforeground="blue",
#                 activebackground="gray",
#                 state=ACTIVE,
#                 # image=photo
#                 )
# button.pack()
# window.mainloop()


# from tkinter import *
# def submit():
#     un = entry.get()
#     print("hello", un)
#     entry.config(state=DISABLED)
# def delete():
#     entry.delete(0, END)
# def backspace():
#     entry.delete(len(entry.get())-1, END)
# window = Tk()
# entry = Entry(window,
#               font=('Arial', 50),
#               fg="white",
#               bg="black",
#               show='$'
#               )
# entry.pack(side=LEFT)
# entry.insert(0,'default')
# submit_button = Button(window, text="submit", command=submit)
# submit_button.pack(side=RIGHT)
# delete_button = Button(window, text="delete", command=delete)
# delete_button.pack(side=RIGHT)
# backspace_button = Button(window, text="backspace", command=backspace)
# backspace_button.pack(side=RIGHT)
# window.mainloop()


# from tkinter import *
# def display():
#     if x.get()==1:
#         print('agree')
#     else:
#         print('disagree')
# window = Tk()
# x = IntVar()
# check_button = Checkbutton(window,
#                            text='i agree sth',
#                            variable=x,
#                            onvalue=1,  # 选中
#                            offvalue=0,  # 未选中
#                            command=display,
#                            font=('Arial', 20),
#                            fg='#3fc',
#                            bg='#cad',
#                            activeforeground='#cad',
#                            activebackground='#3fc')
# # 和button差不多
# check_button.pack()
# window.mainloop()

# from tkinter import *
# def order():
#     print('you ordered',s.get())
# food = ['pizza', 'hamburger', 'HotDog']
# window = Tk()
# s = StringVar()
# for f in food:
#     # indicatoron使其变成一个按钮样式,width给定radio的宽度
#     rb = Radiobutton(window, text=f, variable=s, value=f, indicatoron=0, width=50, command=order)
#     rb.pack(anchor=W)  # 东南西北
#
# window.mainloop()


# from tkinter import *
# def submit():
#     print('the temperature:', str(scale.get()))
# window = Tk()
# scale = Scale(window,
#               from_=100,
#               to=0,
#               length=500,
#               orient=HORIZONTAL,
#               tickinterval=5,
#               resolution=1,
#               showvalue=0,
#               troughcolor="#3fc")  # 从上往下,从左往右,orient表示方向,tickinterval表示显示间隔,resolution是移动的单位,showvalue表示是否显示数值
# scale.set(36)  # 设置scale的值
# scale.pack()
# button = Button(window, text='submit', command=submit)
# button.pack()
# window.mainloop()


# from tkinter import *
# def submit():
#     # print(listbox.get(listbox.curselection()))
#     food = []
#     for c in listbox.curselection():
#         food.append(listbox.get(c))
#     print(food)
# def add():
#     listbox.insert(listbox.size(), entry.get())
#     listbox.config(height=listbox.size())
# def delete():
#     d = []
#     for c in reversed(listbox.curselection()):  # 注意listbox是实时变化的,所以要先删除后面的
#         d.append(c)
#     print(d)
#     for i in d:
#         listbox.delete(i)
#     listbox.config(height=listbox.size())
# window = Tk()
# listbox = Listbox(window,
#                   bg='gray',
#                   font=('Constantia', 35),
#                   width=12,
#                   selectmode=MULTIPLE)
# listbox.pack()
# listbox.insert(1, 'pizza')
# listbox.insert(2, 'salad')
# listbox.insert(3, 'hamburger')
# listbox.config(height=listbox.size())
# submitButton = Button(window, text='submit', command=submit)
# submitButton.pack()
# entry = Entry(window,)
# entry.pack()
# addButton = Button(window, text='add', command=add)
# addButton.pack()
# deleteButton = Button(window, text='delete', command=delete)
# deleteButton.pack()
# window.mainloop()


# from tkinter import *
# from tkinter import messagebox
# def click():
#     # messagebox.showinfo(title='this is an info', message='you clicked a button')
#     if messagebox.askyesno(title='yes/no', message='are you a chinese?'):
#         messagebox.showinfo(title='good luck', message='have a nice day!')
#     else:
#         messagebox.showwarning(title='WARN', message='go away please')
# window = Tk()
# button = Button(window, command=click, text='click me!')
# button.pack()
# window.mainloop()


# 选择颜色
# from tkinter import *
# from tkinter import colorchooser
# def click():
#     color = colorchooser.askcolor()
#     window.config(background=color[1])
#     print(color[0])
# window = Tk()
# window.geometry('360x420')
# button = Button(window, text='click me', command=click)
# button.pack()
# window.mainloop()


# from tkinter import *
# def submit():
#     input = text.get('1.0', END)
#     print(input)
# window = Tk()
# text = Text(window, bg='light yellow', font=('Ink Free', 16), height=10, width=15, padx=2, pady=2)
# text.pack()
# button = Button(window, text='submit', command=submit)
# button.pack()
# window.mainloop()


# tkinter的文件操作
# from tkinter import *
# from tkinter import filedialog
# def openFile():
#     # 初始化打开路径
#     path = filedialog.askopenfilename(initialdir='C:\\Users\\lnpbqc\\PycharmProjects\\pythonProject',
#                                       title='choose a file',
#                                       filetypes=(('text', '*.txt'),
#                                                  ('python', '*.py')))
#     with open(path, 'r', encoding='utf8') as fr:
#         print(fr.read())
# window = Tk()
# button = Button(window, text='open a file', command=openFile)
# button.pack()
# window.mainloop()


# 有中文乱码的问题,暂时没有找到解决办法
# from tkinter import *
# from tkinter import filedialog
# def saveFile():
#     file = filedialog.asksaveasfile(initialdir='C:\\Users\\lnpbqc\\PycharmProjects\\pythonProject',
#                                     defaultextension='.txt',
#                                     filetypes=(('text', '.txt'),
#                                                ('md', '.md'),
#                                                ('others', '.*')))
#     if file is None:
#         return
#     content = str(text.get(1.0, END))
#     file.write(content)
# window = Tk()
# button = Button(window, text='save', command=saveFile)
# button.pack()
# text = Text(window)
# text.pack()
# window.mainloop()


# from tkinter import *
# def start():
#     print('started')
# def stop():
#     print('stopped')
# def restart():
#     print('restarted')
# window = Tk()
# menubar = Menu(window)
# window.config(menu=menubar)
# timeMenu = Menu(menubar)
# menubar.add_cascade(label='operation', menu=timeMenu)
# otherMenu = Menu(menubar, tearoff=0)  # tearoff是分割--
# menubar.add_cascade(label='test', menu=otherMenu)
#
# timeMenu.add_command(label='start', command=start)
# timeMenu.add_separator()
# timeMenu.add_command(label='stop', command=stop)
# timeMenu.add_separator()
# timeMenu.add_command(label='restart', command=restart)
#
# window.mainloop()


# from tkinter import *
# window = Tk()
# frame = Frame(window)
# frame.pack()
# Button(frame, text='W', font=('Ink Free', 16), width=5).pack(side=TOP)
# Button(frame, text='A', font=('Ink Free', 16), width=5).pack(side=LEFT)
# Button(frame, text='S', font=('Ink Free', 16), width=5).pack(side=LEFT)
# Button(frame, text='D', font=('Ink Free', 16), width=5).pack(side=LEFT)
# window.mainloop()


# from tkinter import *
# def createWindow():
#     # Toplevel是一个置顶于父级窗口的窗口
#     # Tk是一个独立的窗口
#     # new_window = Toplevel()
#     new_window = Tk()
#     window.destroy()
# window = Tk()
# Button(window, text='create a new window', font=('Ink Free', 16), command=createWindow).pack(side=TOP)
# window.mainloop()


# from tkinter import *
# from tkinter import ttk
# window = Tk()
# notebook = ttk.Notebook(window)
# tab1 = Frame(notebook)
# tab2 = Frame(notebook)
# notebook.add(tab1, text='tab1')
# notebook.add(tab2, text='tab2')
# notebook.pack(expand=True, fill='both')
# Label(tab1, text='this is tab1').pack()
# Label(tab2, text='this is tab2').pack()
# window.mainloop()


# grid
# from tkinter import *
# def submit():
#     f = fnE.get()
#     l = lnE.get()
#     print(f,l)
# window = Tk()
# fnL = Label(window, text='Your first name:', width=15)
# fnL.grid(row=0, column=0)
# fnE = Entry(window)
# fnE.grid(row=0, column=1)
# lnL = Label(window, text='Your last name:', width=15)
# lnL.grid(row=1, column=0)
# lnE = Entry(window)
# lnE.grid(row=1, column=1)
# Button(window, text='Submit', command=submit).grid(row=2, column=2)
#
# window.mainloop()


# from tkinter import *
# from tkinter.ttk import *
# import time
# def start():
#     total = 1024
#     now = 0
#     speed = 1
#     while now < total:
#         time.sleep(0.05)
#         bar['value'] += (speed/total) * 100
#         now += speed
#         percent.set(str(now / total * 100)+"%")
#         window.update_idletasks()
# window = Tk()
# percent = StringVar()
# bar = Progressbar(window, orient=HORIZONTAL, length=300)
# bar.pack(pady=10, padx=20)
# percentLable = Label(window, textvariable=percent)
# percentLable.pack()
# Button(window, text='Start', command=start).pack()
#
# window.mainloop()


# from tkinter import *
# window = Tk()
# canvas = Canvas(window, height=500, width=500)
# # canvas.create_oval(12, 65, 444, 234, fill='#3fc', width=3)
# # canvas.create_polygon(234, 54, 123, 345, 123, 213, 213, 345)
# canvas.create_arc(0, 0, 500, 500, fill='red', extent=180, width=10)
# canvas.create_arc(0, 0, 500, 500, fill='white', extent=180, start=180, width=10)
# canvas.create_oval(190, 190, 310, 310, fill='white', width=10)
# canvas.pack()
# window.mainloop()


# from tkinter import *
# def doSomething(event):
#     print('nothing', event.keysym)
#     label.config(text=event.keysym)
# window = Tk()
# window.bind('<Key>', doSomething)
# label = Label(window, font=('Ink Free', 20))
# label.pack()
# window.mainloop()


# from tkinter import *
# def doSth(event):
#     print(event)
# window = Tk()
# window.bind('<Button-1>', doSth)
# window.bind('<Button-2>', doSth)
# window.bind('<Button-3>', doSth)
# window.bind('<ButtonRelease>', doSth)
# window.bind('<ButtonPress>', doSth)
# window.bind('<Enter>', doSth)
# window.bind('<Leave>', doSth)
# window.bind('<Motion>', doSth)
# window.mainloop()

# from tkinter import *
# def drag_start(event):
#     widget = event.widget
#     widget.startX = event.x
#     widget.startY = event.y
# def drag_motion(event):
#     widget = event.widget
#     x = widget.winfo_x() - widget.startX + event.x
#     y = widget.winfo_y() - widget.startY + event.y
#     widget.place(x=x, y=y)
# window = Tk()
# frame = Frame(window, width=50, height=50, bg='pink')
# frame.place(x=0, y=0)
# window.bind('<Button-1>', drag_start)
# window.bind('<B1-Motion>', drag_motion)
# window.mainloop()


# from tkinter import *
# def move(event):
#     k = str(event.keysym).lower()
#     if k == 'w':
#         label.place(x=label.winfo_x(), y=label.winfo_y()-1)
#
#     if k == 's':
#         label.place(x=label.winfo_x(), y=label.winfo_y()+1)
#
#     if k == 'a':
#         label.place(x=label.winfo_x()-1, y=label.winfo_y())
#
#     if k == 'd':
#         label.place(x=label.winfo_x()+1, y=label.winfo_y())
# window = Tk()
# # window
# window.geometry("500x500")
# photo = PhotoImage(file='learn.png')
# label = Label(window, image=photo)
# label.pack()
# window.bind('<Key>', move)
# window.mainloop()


# from tkinter import *
# def move(event):
#     k = str(event.keysym).lower()
#     if k == 'w':
#         canvas.move(image, 0, -1)
#
#     if k == 's':
#         canvas.move(image, 0, 1)
#
#     if k == 'a':
#         canvas.move(image, -1, 0)
#
#     if k == 'd':
#         canvas.move(image, 1, 0)
# window = Tk()
# canvas = Canvas(window, width=500, height=500)
# canvas.pack()
# photo = PhotoImage(file='learn.png')
# image = canvas.create_image(0, 0, image=photo, anchor=NW)
# window.bind('<Key>', move)
# window.mainloop()


# from tkinter import *
# import time
# import random
# WIDTH = 500
# HEIGHT = 500
# flag = True
# imX = 1
# imY = 1
# def stop(event):
#     global flag
#     if event.keysym == 'space':
#         flag = False
# window = Tk()
# canvas = Canvas(window, width=WIDTH, height=HEIGHT)
# canvas.pack()
# photo = PhotoImage(file='learn.png')
# imgW = photo.width()
# imgH = photo.height()
# image = canvas.create_image(0, 0, image=photo, anchor=NW)
# window.bind('<Key>', stop)
# while flag:
#     coordinates = canvas.coords(image)
#     if coordinates[0] > (WIDTH - imgW) or coordinates[0] < 0:
#         imX = -imX
#     if coordinates[1] > (HEIGHT - imgH) or coordinates[1] < 0:
#         imY = -imY
#     xv = random.random() * 10 * imX
#     yv = random.random() * 10 * imY
#     print(coordinates)
#
#     canvas.move(image, xv, yv)
#
#     window.update()
#     time.sleep(0.01)
# window.mainloop()


# from tkinter import *
# import random
# import time
# from img import Img
# # class Img:
# #     def __init__(self, canvas, x, y, image, xv, yv):
# #         self.canvas = canvas
# #         self.image = self.canvas.create_image(x, y, image=image, anchor=NW)
# #         self.xv = xv
# #         self.yv = yv
# #         self.width = image.width()
# #         self.height = image.height()
# #
# #     def move(self):
# #         coordinates = self.canvas.coords(self.image)
# #         if coordinates[0] > self.canvas.winfo_width()-self.width or coordinates[0] < 0:
# #             self.xv = -self.xv
# #         if coordinates[1] > self.canvas.winfo_height()-self.height or coordinates[1] < 0:
# #             self.yv = -self.yv
# #         self.canvas.move(self.image, self.xv, self.yv)
#
# WIDTH = 1000
# HEIGHT = 1000
# flag = True
# def stop(event):
#     global flag
#     if event.keysym == 'space':
#         flag = False
# window = Tk()
# window.title("press space to stop")
# canvas = Canvas(window, width=WIDTH, height=HEIGHT)
# canvas.pack()
# photo = PhotoImage(file='learn.png')
# window.bind('<Key>', stop)
# image = []
# while flag:
#     if len(image) < 1314:
#         image.append(Img(canvas, random.randint(0, WIDTH), random.randint(0, HEIGHT), photo, random.random()*10, random.random()*10))
#     for i in range(len(image)):
#         image[i].move()
#     window.update()
#     time.sleep(0.001)
# window.mainloop()


# clock programmer
# from tkinter import *
# from time import *
# def update():
#     time_string = strftime("%H:%M:%S %p")
#     time_label.config(text=time_string)
#     day_string = strftime("%y-%m-%d %A")
#     day_label.config(text=day_string)
#     time_label.after(1000, update)
#
# window = Tk()
# time_label = Label(window, font=('Arial', 20), fg='white', bg='black')
# time_label.pack()
# day_label = Label(window, font=('Ink Free', 20), fg='gray', bg='light yellow')
# day_label.pack()
# update()
# window.mainloop()


# python 使用邮件
# import smtplib
# sender = 'sender@qq.com'
# password = '***********'
# receiver = 'receiver@qq.com'
# subject = 'Python email test'
# body = 'this is a test for email'
# message = f"""
# from:{sender}
# to:{receiver}
# subject:{subject}
# \t{body}
# """
# try:
#     server = smtplib.SMTP("smtp.qq.com", 587)  # 不知道这个
#     server.starttls()
#     server.login(sender, password)
#     print("logining")
#     server.sendmail(sender, receiver, message)
#     print("email has been sent")
# except smtplib.SMTPAuthenticationError:
#     print("cannot login")


# 此程序有误,需修改才能使用
# 计算器
# from tkinter import *
# def button_press(num):
#     # global equation_text
#     # equation_text = equation_text + str(num)
#     # equation_label.set(equation_text)
#     print(num)
# def equals():
#     pass
# def clear():
#     pass
# window = Tk()
# window.title("calculator")
# equation_text = ""
# equation_label = StringVar()
# label = Label(window, textvariable=equation_label, font=("Ink Free", 16))
# label.pack()
# frame = Frame(window)
# frame.pack()
# for i in range(0, 10):
#     if i == 9:
#         Button(frame, text=0, height=4, width=9, font=16, command=lambda: button_press(0)).grid(row=3, column=1)
#     else:
#         Button(frame, text=(i+1), height=4, width=9, font=16, command=lambda: button_press(i+1)).grid(row=int(i/3), column=i % 3)  # lambda表达式返回buttonpress 的地址
# operators = ['+', '-', '*', '/']
# for i in operators:
#     Button(frame, text=i, height=4, width=9, font=16, command=lambda: button_press(i)).grid(row=operators.index(i, 0, 4), column=3)
# Button(frame, text='=', height=4, width=9, font=16, command=equals).grid(row=3, column=2)
# window.mainloop()


# import os
# from tkinter import *
# from tkinter import filedialog, colorchooser, font
# from tkinter.messagebox import *
# from tkinter.filedialog import *
# def change_color():
#     color = colorchooser.askcolor(title='pick a color you like')
#     text_area.config(fg=color[1])
# def change_font(*args):
#     text_area.config(font=(font_name.get(), font_size.get()))
# def new_file():
#     window.title('Untitled')
#     text_area.delete(1.0, END)
# def open_file():
#     file = askopenfilename(defaultextension='.txt',
#                            file=[('All', '*.*'),
#                                  ('Text', '*.txt')])
#     if file != '':
#         window.title(os.path.basename(file))
#         text_area.delete(1.0, END)
#         with open(file, 'r') as f:
#             text_area.insert(1.0, f.read())
#
# def save_file():
#     file = asksaveasfilename(initialfile='untitled.txt',
#                              defaultextension='.txt',
#                              filetypes=[('ALl', '*.*'),
#                                         ('Text', '*.txt')])
#     if file != '':
#         window.title(os.path.basename(file))
#         with open(file, 'w') as f:
#             f.write(text_area.get(1.0, END))
# def cut():
#     text_area.event_generate("<<Cut>>")
# def copy():
#     text_area.event_generate("<<Copy>>")
# def paste():
#     text_area.event_generate("<<Paste>>")
# def about():
#     showinfo("About", "this is a python program written by lnpbqc with the help of Bro Code")
# def quit():
#     window.destroy()
# window = Tk()
# window.title('Editor')
# file = None
# width = 500
# height = 500
# screen_width = window.winfo_screenwidth()
# screen_height = window.winfo_screenheight()
# # 横纵坐标
# x = int((screen_width/2)-(width/2))
# y = int((screen_height/2)-(height/2))
# window.geometry("{}x{}+{}+{}".format(width, height, x, y))
# font_name = StringVar(window)
# font_name.set('Ink Free')
# font_size = StringVar(window)
# font_size.set("20")
# text_area = Text(window, font=(font_name.get(), font_size.get()))
# scroll_bar = Scrollbar(text_area)
# window.grid_rowconfigure(0, weight=1)
# window.grid_columnconfigure(0, weight=1)
# text_area.grid(sticky=N+E+W+S)
# scroll_bar.pack(side=RIGHT, fill=Y)
# text_area.config(yscrollcommand=scroll_bar.set)
#
# frame = Frame(window)
# frame.grid()
# color_button = Button(frame, text='color', command=change_color)
# color_button.grid(row=0, column=0)
# font_box = OptionMenu(frame, font_name, *font.families(), command=change_font)
# font_box.grid(row=0, column=1)
# size_box = Spinbox(frame, from_=1, to=100, textvariable=font_size, command=change_font)
# size_box.grid(row=0, column=2)
#
# menu_bar = Menu(window)
# window.config(menu=menu_bar)
#
# file_menu = Menu(menu_bar, tearoff=0)
# menu_bar.add_cascade(label='File', menu=file_menu)
# file_menu.add_command(label='New', command=new_file)
# file_menu.add_command(label='Open', command=open_file)
# file_menu.add_command(label='Save', command=save_file)
# file_menu.add_separator()
# file_menu.add_command(label='Exit', command=quit)
#
# edit_menu = Menu(menu_bar, tearoff=0)
# menu_bar.add_cascade(label='Edit', menu=edit_menu)
# edit_menu.add_command(label='Cut', command=cut)
# edit_menu.add_command(label='Copy', command=copy)
# edit_menu.add_command(label='Paste', command=paste)
#
# help_menu = Menu(menu_bar, tearoff=0)
# menu_bar.add_cascade(label='Help', menu=help_menu)
# help_menu.add_command(label='About', command=about)
#
# window.mainloop()


# 贪吃蛇
from tkinter import *
from tkinter import messagebox
import random
import time
WIDTH = 700
HEIGHT = 700
SPEED = 250
SPACE_SIZE = 50
BODY_PARTS = 3
SNAKE_COLOR = "green"
BACKGROUND_COLOR = 'black'
FOOD_COLOR = "orange"
class Snake:
    def __init__(self):
        self.body_size = BODY_PARTS
        self.coordinates = []
        self.squares = []
        for i in range(0, BODY_PARTS):
            self.coordinates.append([0, 0])
        for x, y in self.coordinates:
            square = canvas.create_rectangle(x, y, x + SPACE_SIZE, y + SPACE_SIZE, fill=SNAKE_COLOR)
            self.squares.append(square)
class Food:
    def __init__(self):
        x = random.randint(0, (WIDTH / SPACE_SIZE) - 1) * SPACE_SIZE  # 700/50=14
        y = random.randint(0, (HEIGHT / SPACE_SIZE) - 1) * SPACE_SIZE
        self.coordinates = [x, y]
        canvas.create_oval(x, y, x + SPACE_SIZE, y + SPACE_SIZE, fill=FOOD_COLOR, tag='food')
def next_turn(snake, food):
    x, y = snake.coordinates[0]
    if direction == 'up':
        y -= SPACE_SIZE
    elif direction == 'down':
        y += SPACE_SIZE
    elif direction == 'left':
        x -= SPACE_SIZE
    elif direction == 'right':
        x += SPACE_SIZE
    snake.coordinates.insert(0, (x, y))
    square = canvas.create_rectangle(x, y, x + SPACE_SIZE, y + SPACE_SIZE, fill=SNAKE_COLOR)
    snake.squares.insert(0, square)
    if x == food.coordinates[0] and y == food.coordinates[1]:
        global score
        score += 1
        label.config(text="Score:{}".format(score))
        canvas.delete("food")
        food = Food()
        flag = True
        while flag:
            for s in snake.coordinates:
                if s[0] == food.coordinates[0] and s[1] == food.coordinates[1]:
                    flag = True
                    break
                else:
                    flag = False
            if flag:
                food = Food()
    else:
        del snake.coordinates[-1]
        canvas.delete(snake.squares[-1])
        del snake.squares[-1]
    if check_collisions(snake):
        game_over()
    window.after(SPEED, next_turn, snake, food)
def change_direction(new_direction):
    global direction
    if new_direction == 'left':
        if direction != 'right':
            direction = new_direction
    elif new_direction == 'up':
        if direction != 'down':
            direction = new_direction
    elif new_direction == 'down':
        if direction != 'up':
            direction = new_direction
    elif new_direction == 'right':
        if direction != 'left':
            direction = new_direction
def check_collisions(snake):
    x, y = snake.coordinates[0]
    if x < 0 or x >= WIDTH:
        return True
    elif y < 0 or y >= HEIGHT:
        return True
    for body in snake.coordinates[1:]:
        if x == body[0] and y == body[1]:
            return True
    return False
def game_over():
    canvas.delete(ALL)
    messagebox.showerror('GAME OVER', 'you have lost it')
    canvas.create_text(canvas.winfo_width()/2, canvas.winfo_height()/2,
                       font=('Ink Free', 60), text='GAME OVER', fill='red', tag='gameover')
    window.update()
    time.sleep(3)
    window.destroy()

window = Tk()
window.title('snake game')
window.resizable(False, False)
score = 0
direction = 'down'
label = Label(window, text='Score:{}'.format(score), font=('Ink Free', 30))
label.pack()

canvas = Canvas(window, bg=BACKGROUND_COLOR, height=HEIGHT, width=WIDTH)
canvas.pack()

window.update()
# 窗口宽高
window_width = window.winfo_width()
window_height = window.winfo_height()
# 屏幕宽高
screen_width = window.winfo_screenwidth()
screen_height = window.winfo_screenheight()
x = int((screen_width / 2) - (window_width / 2))
y = int((screen_height / 2) - (window_height / 2))
window.geometry("{}x{}+{}+{}".format(window_width, window_height, x, y))
window.bind('<a>', lambda e: change_direction('left'))
window.bind('<s>', lambda e: change_direction('down'))
window.bind('<d>', lambda e: change_direction('right'))
window.bind('<w>', lambda e: change_direction('up'))
snake = Snake()
food = Food()
next_turn(snake, food)

window.mainloop()

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值