[Don't bother with Python] Python basic tutorial study notes and code

2 print

print(1)

String print('') print("")

print('I\'m yan') If you add a single quote after the slash, it will not be judged as the end single quote of the string

The green in the brackets indicates the string, and the black indicates the command

a = 2
b = a*3
print(a,b)
>>> print(1)
1
>>> print('We are')
We are
>>> print("we are going")
we are going
>>> print('I\'m yan')
I'm yan
>>> print('apple'+'car')
applecar
>>> print('apple'+4)
Traceback (most recent call last):
  File "<pyshell#11>", line 1, in <module>
    print('apple'+4)
TypeError: can only concatenate str (not "int") to str
>>> print('apple'+'4')
apple4
>>> print('apple'+str(4))
apple4
>>> print(1+2)
3
>>> print('1+2')
1+2
>>> print(int('1')+2)
3
>>> print('1.2'+2)
Traceback (most recent call last):
  File "<pyshell#17>", line 1, in <module>
    print('1.2'+2)
TypeError: can only concatenate str (not "int") to str
>>> print(float('2.3')+2)
4.3

3 mathematics

add + reduce- take* remove/ power** Take the remainder % Rounding//
>>> 1+1
2
>>> 1-1
0
>>> 2*2
4
>>> 3**2
9
>>> 2**4
16
>>> 8%2
0
>>> 8%3
2
>>> 7/3
2.3333333333333335
>>> 9//4
2
>>> 10//3
3
>>> 10/2
5.0

4 independent variables

File-New file

a = 1
b = 2
c = 3
print(a,b,c)

or written as

a,b,c=1,2,3
print(a,b,c)

Argument operation

a=2
b=a*3
print(a,b)

Runtime Run-Run Module

5 while loop

condition = 1
while condition < 10:
    print (condition)
    condition = condition + 1

When the loop continues, use ctrl+c to jump out

while True:
    print("I'm True")

6 for loop

The statements inside the for loop are written after four spaces, such as the following print and inner statements, and the following outer statements are outside the for.

In addition, if I use for in the list, i will automatically increase by 1?

examp1e_1ist = [1,2,3,4,5,6,7,12,254,564,23,4,5,6]

for i in examp1e_1ist:
    print(i)
    print (' inner of for')
    
print (' outrt of for')

operation result:

1
 inner of for
2
 inner of for
3
 inner of for
4
 inner of for
5
 inner of for
6
 inner of for
7
 inner of for
12
 inner of for
254
 inner of for
564
 inner of for
23
 inner of for
4
 inner of for
5
 inner of for
6
 inner of for
 outrt of for

Select the statement contained in for, press and hold CTRL+[ or CTRL+] to move the statement as a whole left and right.

The output of range including head and tail (4, 10) is 4-9

for i in range(4,10):
    print(i)

operation result:

4
5
6
7
8
9

range(a,b,step) means from a to b, and the step is step

for i in range(4,10,4):
    print(i)

operation result:

4
8

After opening the opening bracket, a yellow usage introduction box is displayed
insert image description here

7 if condition

The size can be judged continuously, instead of judging x<y as 1 first and then judging 1>z like C language.

Instead, it is judged whether x<y, y>z is established at the same time.

x=1
y = 2
z= 1

if x < y >z:
    print ('yes')

The running result is yes.

If the continuous judgment is incorrect, yes will not be output

greater than or equal to >= less than or equal to <= Equal judgment == not equal to! =

8 if else condition

The if else is in the same position and both are followed by a colon.

x=5
y= 3
z= 9

if x <y :
    print('x < y')
else:
    print('x >= y')

operation result:

x >= y

9 if elif else

After the first condition of if is met, the if elif else statement will jump out

x=5
y =3
z= 9

if x > 8:
    print('x >8')
elif x <=8:
    print ('x <= 8')
elif x <6:
    print('x < 6')
print( 'finish ifelse' )

operation result:

x <= 8
finish ifelse

10 def function

Define a function named function or other, and then use the function name on the command line to call.
insert image description here

Or directly call the function after defining the function in the script, and run it directly.

def function():
    print ('this is a function')
    a =1 +2
    print(a)

function()

11 Functions, parameters

def fun(a, b) :
    c = a*b
    print(' c=a*b=', c)

>>> fun(4,7)
 c=a*b= 28
>>> fun(b=6,a=3)
 c=a*b= 18

The output is replaced and converted into a string. The + sign at this time means to connect the two strings

def multip1y(a,b):
    c = a*b
    print(str(c)+"="+str(a) +"*"+str(b))
>>> multip1y(6,8)
48=6*8

In Python, f-strings (or format strings) are a convenient way of formatting strings to interpolate the value of a variable into a string. Within an f-string, curly braces {} can be used to enclose variable names that will be replaced with their values ​​at runtime.

def multiply(a,b):
    c=a*b
    print(f'{
      
      c}={
      
      a}*{
      
      b}')
>>> multiply(3,6)
18=3*6

12 Function default parameters

assignment via function

def sale_car (price,color,brand,is_second_hand) :
    print (' price:',price,
    'co1or:',color,
    'brand:',brand,
    'is_second_hand:',is_second_hand)

sale_car (10203,'red', 'carry', True)
 price: 10203 co1or: red brand: carry is_second_hand: True

1 is the default parameter assignment, and 2 is the need to modify the content in the function. It can be observed that the output is changed to blue.
insert image description here
The value that needs to be defined cannot be behind the default defined value, otherwise an error will be reported. The brand needs to be defined as follows, and if it is placed behind the defined color, an error will be reported.
insert image description here
run after changing position
insert image description here

13 Global & local variables, global & local

APPLE is a global variable, a is a local variable, and an error will be reported for all printing locals

APPLE=100

def fun():
    a= 10
    return a+100

print (APPLE)
print(a)
100
Traceback (most recent call last):
  File "C:/Users/Desktop/python_exercise/pyyy.py", line 8, in <module>
    print(a)
NameError: name 'a' is not defined

print function return value

APPLE=100

def fun():
    a= APPLE
    return a+100

print (APPLE)
print(fun())
100
200

It is reasonable to put global variables outside. If you must put the global in the function, use global.

Before running, a is none, and after running the fun function, a becomes 20. (In this case, you must remember to assign a value at the front)

a =None
def fun():
    global a
    a= 20
    return a+100

print('a past is', a)
print(fun())
print('a now is', a)
a past is None
120
a now is 20

If there is no global a statement, a is still none after running

a =None
def fun():
    a= 20
    return a+100

print('a past is', a)
print(fun())
print('a now is', a)
a past is None
120
a now is None

15 Reading and writing files

Write

If there is no file name in open(), a file with the corresponding name will be generated, and w means write operation.

The written content represents (text) in the first line, where \n means newline

After writing, you must remember to close the document, so close

text = "This is my first text.\nThis is next line.\nThis is last 1ine."
my_py_fi1e=open(' my_py_file.txt','w')
my_py_fi1e. write(text)
my_py_fi1e.close()

After running, a txt will be generated in the storage location of this program, and its content is what we wrote.

rewrite

If you directly write add a new line, the original original will be cleared and new content will be written

text = "This is my first text.\nThis is next line.\nThis is last 1ine."
my_py_fi1e=open(' my_py_file.txt','w')
my_py_fi1e. write('add a new line')
my_py_fi1e.close()

as follows
insert image description here

attach

If we change the write after open to append (w is changed to aa to indicate append)

text = "This is my first text.\nThis is next line.\nThis is last 1ine."
append_txt='\nadd a new line'
my_py_fi1e=open(' my_py_file.txt','a')
my_py_fi1e. write(append_txt)
my_py_fi1e.close()

At this point the txt content becomes
insert image description here

read

my_fi1e = open(' my_py_file.txt','r')
counter = my_fi1e.read()
print(counter)
This is my first text.
This is next line.
This is last 1ine.
add a new line

readline means read line, read line by line

my_fi1e=open(' my_py_file.txt','r')
counter = my_fi1e.readline()
second_read =my_fi1e.readline()
print (counter, second_read)
This is my first text.
 This is next line.

readlines means all read

my_fi1e=open(' my_py_file.txt','r')
counter = my_fi1e.readlines()
print (counter)
['This is my first text.\n', 'This is next line.\n', 'This is last 1ine.\n', 'add a new line']

18 classes

Class class, the general class is named with the first letter capitalized.

class Calculator:
    name = 'Good ca1cu1ator'
    price = 18
    def add(x, y):
        result =x+y
        print (result)
    def minus (x,y):
        result =x-y
        print (result)
    def times(x,y):
        result =x*y
        print (result)
    def divide(x, y) :
        result = x/y
        print (result)
>>> cal = Calculator
>>> cal.name
'Good ca1cu1ator'
>>> cal.price
18
>>> cal.minus(9,14)
-5
>>> cal.times(4,8)
32
>>> cal.divide(7,2)
3.5

19 class init function

Note that there are two short lines on the left and right of the initialization here - init -, and self should be used in parentheses

class Calculator:
    def __init__(self,name,price,hight=20,width=16,weight=18):
       self.n = name
       self.p = price
       self.h = hight
       self.wi = width
       self.we = weight
    def add(self,x,y):
        result = x + y
        print(result)
    def minus(self,x,y):
        result = x-y
        print(result) 
    def times(self,x,y):
        result = x*y
        print(result)
    def divide(self,x,y):
        result = x/y
        print(result)
>>> c=Calculator('yuan',1)
>>> c.n
'yuan'
>>> c.p
1
>>> c.h
20
>>> c.we
18
>>> c.wi
16

When using a class, you must remember to add self, otherwise an error will appear

Self.add is used in the following initialization. If there is no self in the brackets of the function defined below, an error will be reported, so an addition will be calculated at the beginning.

Similarly, using c.we in the command line without adding self will also report an error.

20 inputInput

input returns a string

a_input = input (' P1ease give a number : ')
print ('This input number is',a_input)

The string judgment of the input is judged by str(1) or '2' represented by a string.

a_input = input (' P1ease give a number: ')
if a_input == str(1):
    print ('This is a good one')
elif a_input == '2':
    print (' see you')
else :
     print ('Good luck')

Or convert the input data to an int type before making a judgment

21 Tuples & Lists

A tuple is represented as (1, 2, 3, 4, 7) or 1, 2, 5, 7, 8. That is, within parentheses or without parentheses.

list list[12,4,3,5,6]

a_tup1e =(2,5,6,7,4)
b_tup1e=5,6,3,2

a_list =[3,6,76,3,6]

for x in a_list:
    print(x)

operation result:

3
6
76
3
6

insert image description here

len means the length, for example, len(a_tuple) here is 5, and range(5) is 0-4. At this time, 0-4 of a_tuple is output, which is all numbers.

Although the representations of tuples and lists are different, the square brackets [] are used in print so that no error will be reported. If parentheses () are used, an error will appear.

insert image description here

22 list list

increase (append)

Append is added after the list

insert image description here

insert

insert at the specified position in the list

Here it means inserting 99 at the 2 positions of 0, 1, 2

insert image description here

remove

remove means to remove the value, not the index bit. For example, remove(5) means to remove the first 5 in the list. Note that only the first 5 will be removed.

insert image description here

Contact twice to remove 5

insert image description here

index

index position

When indexing, -1, -2, etc. can be used to indicate the last digit of the index, the reciprocal digit, etc.

insert image description here

The index a[0:3] actually indexes bits 0, 1, and 2 (including the head but not the tail). a[:3] indicates the position from the front to 2, as follows

insert image description here

a[-3:] can also represent the last third digit

insert image description here

index value

The position of the index value 9, you can use index to know that 9 is in the 4th position (01234)

insert image description here

count (count)

List a, count the number of 5, which is 3

insert image description here

sort

sort will sort the list from small to large, and will overwrite the original a after sorting, so it is still print(a) at this time, not print(a.sort())

insert image description here

If you want to sort from big to small, use sort(reverse=True)

insert image description here

23 multidimensional list

sort

sort will sort the list from small to large, and will overwrite the original a after sorting, so it is still print(a) at this time, not print(a.sort())

insert image description here

If you want to sort from big to small, use sort(reverse=True)

insert image description here

a=[1,5,3,5,9,5,2]
multi_dim_a=[[1,2,3],[4,5,6],[7,8,9]]
print('a[3]=',a[3])
print('multi_dim_a[2][1]=',multi_dim_a[2][1])

Running results ([2][1] in multidimensional means 012, 2 and 1 of 01):

a[3]= 5
multi_dim_a[2][1]= 8

24 dictionaries

Note that the index when printing still uses [ ] instead of { }, and the content of the dictionary is also [ ].

d={
    
    'apple':3,'pear':7,'orange':9}   #字典
print('d=',d)
print('d[orange]=',d['orange'])

del d['pear']   #删除pear
print('deleted prar d=',d)

d['b'] = 20 #增加字典内容
d['pig'] = 100
d[1]= 12
print('add d=',d)

operation result:

d= {
    
    'apple': 3, 'pear': 7, 'orange': 9}
d[orange]= 9
deleted prar d= {
    
    'apple': 3, 'orange': 9}
add d= {
    
    'apple': 3, 'orange': 9, 'b': 20, 'pig': 100, 1: 12}

At the same time, dictionaries, lists, etc. can also be placed in the dictionary, such as printing out the content of 3 in apple in the dictionary.

d={
    
    'apple':{
    
    1:11,3:33,4:44},'pear':[3,7,9,2],'orange':9}   #字典
print(d['apple'][3])

The running result is 33.

25 import

import time module, display the time of course after running.

import time

print(time.localtime())

Or, for the convenience of writing, name time as t, and it will have the same effect after running.

import time as t

print(t.localtime())

If you only need to use individual content, you can write from xxx import xxx,xxx

from time import time,localtime
# 此时运用就不需要前缀time.XXX

print(localtime())
print(time())

Import all functions in time with *

from time import *
# 此时运用就不需要前缀time.XXX

print(localtime())
print(time())

26 own modules

Create your own module, write a module such as module1 in the script, that is, the file name needs to be named module1

def add(a,b):
    c=a+b
    print('a+b=',c)

To call, you need to create a new script in the same directory as the module just created

import module1 as m

m.add(5,8)

running result:

a+b= 13

For python's default built-in modules, you don't need to keep them in the same directory, so you can put them in the default path for useful modules you create later, and then import them directly. The default path is generally placed in python\Lib\site-packages.

27 continue&break

When not continue or break

a = True
while a:
    b = input('type something=')#input的内容被当作字符串
    if b== '1':
        a = False
    else:
        pass
    print('still in while')

print('finish run')

Running result ( when b==1, it does not jump out of the loop, but executes all the rest before ending ):

type something=2
still in while
type something=1
still in while
finish run

When break is used, if it is not 1, it will print and continue the loop; if it is 1, it will jump out of the loop and print finish.

while True:
    b = input('type something=')#input的内容被当作字符串
    if b== '1':
        break
    else:
        pass
    print('still in while')

print('finish run')

operation result:

type something=3
still in while
type something=5
still in while
type something=1
finish run

When using continue, if it is not 1, the print continues to loop, and when it is 1, continue to execute the content in while.

while True:
    b = input('type something=')#input的内容被当作字符串
    if b== '1':
        continue
    else:
        pass
    print('still in while')

print('finish run')

operation result:

type something=2
still in while
type something=1
type something=

28 Error handling try...except...else

The following is the syntax of a simple try...except...else:

try:
<语句>        #运行别的代码
except <名字><语句>        #如果在try部份引发了'name'异常
except <名字><数据>:
<语句>        #如果引发了'name'异常,获得附加的数据
else:
<语句>        #如果没有异常发生

The working principle of try is that when a try statement is started, python marks the context of the current program so that when an exception occurs, it can return here. The try clause is executed first, and what happens next depends on the execution time Is there an exception.

  • If an exception occurs when the statement after the try is executed, python jumps back to the try and executes the first except clause that matches the exception. exception).

  • If an exception occurs in the statement after try, but there is no matching except clause, the exception will be submitted to the upper try, or to the top of the program (this will end the program and print the default error message).

  • If no exception occurs during the execution of the try clause, python will execute the statement after the else statement (if there is an else), and then control flow through the entire try statement.
    The script code is as follows (run the first time, enter y to create a file, and run the second time to write content ssss to the file):

try:
    file=open('eeee','r+')
except:
    print('there is no file named eeee')
    response = input('do you want to creat a file?')
    if response =='y':
        file = open('eeee','w')
    else:
        pass
else:
    file.write('ssss')
file.close()

The open('filename', 'r+') is a way to open the file, where 'r+' means to open the file in read-write mode. This means that the contents of the file can be read and written to. If the file does not exist, a new one will be created. If the file already exists, reading and writing will start from the beginning of the file.

29 zip lambda map

>>> a =[1,2,3]
>>> b = [4,5,6]
>>> zip(a,b)
<zip object at 0x0000026ED9494148>	#运行结果,为一个object,不显示内容
>>> list(zip(a,b))					#放在list中显示
[(1, 4), (2, 5), (3, 6)] #运行结果
>>> for i,j in zip(a,b):
	print(i/2,j*2)

0.5 8					#运行结果
1.0 10
1.5 12

>>> list(zip(a,b,a))	#zip三组
[(1, 4, 1), (2, 5, 2), (3, 6, 3)]	#运行结果

>>> def fun1(x,y):
	return(x+y)

>>> fun1(4,6)
10					#运行结果
>>> fun2 = lambda x,y:x+y	#运行结果,lambda可以实现def同样的功能
>>> fun2(4,6)
10					#运行结果
>>> map(fun1,[1],[2])
<map object at 0x0000026ED9494048>	#运行结果,为一个object,不显示内容
>>> list(map(fun1,[1],[2]))
[3]						#运行结果
>>> list(map(fun1,[1,4],[5]))
[6]						#运行结果,如果不对应,只计算前一组
>>> list(map(fun1,[1,4],[5,8]))
[6, 12]					#运行结果

30 shallow copy & deep copy (copy&deepcopy)

Directly use the assignment b=a, the id of the two is the same, it can be understood that a and b are the same thing. Changing one of them will also change the other at the same time, and the id remains the same.

a=[1,5,7]
>>> b=a
>>> id(a)
1815267812296
>>> id(b)
1815267812296
>>> a[0]=10		#改变a,b也同时改变
>>> b
[10, 5, 7]
>>> b[1]=20		#改变b,a也同时改变
>>> a
[10, 20, 7]
>>> id(a)==id(b)
True
>>> id(a[0])==id(b[0])
True
>>> id(a[1])==id(b[1])
True
>>> id(a[2])==id(b[2])
True

copy is a shallow copy, which will copy shallow things to other ids, and deep ones cannot be copied, so the id remains unchanged.

>>> a=[1,2,3]
>>> import copy
>>> c=copy.copy(a)
>>> id(a)==id(c)
False
>>> id(a[0])==id(c[0])  #各个位的值id为什么相同啦,推测是他们表示的是一个相同的数,而找的同一个数的id是相同的
True
>>> id(a[1])==id(c[1])
True
>>> id(a[2])==id(c[2])
True
>>> a[1]=1111	#被复制到别的id,改变a,c不变
>>> c
[1, 2, 3]
>>> a
[1, 1111, 3]
>>> c[1]=2222	#被复制到别的id,改变c,a不变
>>> a
[1, 1111, 3]
>>> c
[1, 2222, 3]

Next try the copy of the deep list

>>> a=[1,2,[3,4]]
>>> import copy
>>> d=copy.copy(a)
>>> d
[1, 2, [3, 4]]
>>> id(a)==id(d)
False
>>> a[0]=33		#改变a,d不变
>>> d
[1, 2, [3, 4]]
>>> a
[33, 2, [3, 4]]
>>> d[1]=55		#改变d,a不变
>>> a
[33, 2, [3, 4]]
>>> d
[1, 55, [3, 4]]

>>> d[2][0]=88		#改变d内列表中的第0个值后,a也同时改变
>>> a
[33, 2, [88, 4]]
>>> a[2][1]=99		#改变a内列表中的第1个值后,d也同时改变
>>> d
[1, 55, [88, 99]]

Next use deepcopy, which is a complete copy to another id, changing one will not affect the content of the other copy.

>>> import copy
>>> a=[1,2,[3,4]]
>>> e =copy.deepcopy(a)
>>> e
[1, 2, [3, 4]]
>>> id(a) ==id(e)
False
>>> e[2][0]=55
>>> a
[1, 2, [3, 4]]
>>> e
[1, 2, [55, 4]]
>>> a[2][1]=77
>>> e
[1, 2, [55, 4]]
>>> a
[1, 2, [3, 77]]

31 Threading Multithreading

Threading multithreading series video
Python3 multithreading

1 What is multithreading

Multithreading is similar to executing multiple different programs at the same time. Multithreading has the following advantages:

  • Using threads can put the tasks in the program that take a long time into the background for processing.
  • The user interface can be more attractive. For example, when the user clicks a button to trigger the processing of certain events, a progress bar can pop up to show the progress of the processing.
  • Programs may run faster.
  • In the implementation of some waiting tasks, such as user input, file reading and writing, and network sending and receiving data, threads are more useful. In this case we can release some precious resources such as memory usage and so on.

Each independent thread has an entry point for program execution, a sequential execution sequence, and an exit point for the program. However, threads cannot be executed independently, and must depend on the application program, and the application program provides multiple thread execution control.

Each thread has its own set of CPU registers, called the thread's context, which reflects the state of the CPU registers the last time the thread ran the thread.

The instruction pointer and stack pointer registers are the two most important registers in the thread context. The thread always runs in the context of the process. These addresses are used to mark the memory in the process address space that owns the thread.

  • Threads can be preempted (interrupted).
  • Threads can be temporarily put on hold (also known as sleeping) while other threads are running - this is thread yielding.

Threads can be divided into:

  • Kernel threads : Created and revoked by the operating system kernel.
  • User thread : A thread implemented in a user program without kernel support.

The two modules commonly used in Python3 threads are:

  • _thread
  • threading (recommended)

The thread module has been deprecated. Users can use the threading module instead. Therefore, the "thread" module can no longer be used in Python3. For compatibility, Python3 renames thread to "_thread".

2 Add thread add thread

import threading

def thread_job():
    print('This is an added,number is %s\n'% threading.current_thread())
def main():
    added_thread=threading.Thread(target=thread_job)
    added_thread.start()
    print(threading.active_count()) #激活的线程数
    print(threading.enumerate())    #返回当前活动的 Thread 对象列表
    print(threading.current_thread())#返回当前正在执行的线程对象

if __name__=='__main__':#判断是否为主模块,如果是,则运行main()函数
    main()

Among them, %s is a placeholder, indicating the string representation of the variable or expression to be replaced later. The specific replacement value is provided by the content after the % symbol, here is the thread object returned by the threading.current_thread() function.

If the type of the placeholder is a string, you can use %s; if the type of the placeholder is an integer, you can use %d; if the type of the placeholder is a floating point number, you can use %f.
Examples are as follows:

name = 'John'
age = 30
height = 1.75

print('My name is %s, I am %d years old, and I am %f meters tall.' % (name, age, height))

3 join

In Python, the join() method is a method of the Thread class (Thread), which is used to wait for a thread to complete execution .
When the join() method of another thread is called in one thread, the current thread will block until the called thread finishes executing or times out .

The join() method is often used in multi-threaded programming to wait for all sub-threads to finish executing in the main thread before continuing to execute the subsequent code of the main thread. If the join() method is not used, the main thread may end while the child thread is still executing, causing the child thread to fail to complete the task.

The join() method can pass in a parameter indicating the maximum waiting time. If the called thread has not finished executing within the specified time, the join() method will return and continue to execute the subsequent code of the current thread. If no parameters are passed in, it will wait until the called thread finishes executing.

import threading
import time
def T1_job():
    print('T1 start\n')
    for i in range(10):
        time.sleep(0.1)
    print('T1 finishi\n')

def T2_job():
    print('T2 start\n')
    print('T2 finish\n')

def main():
    thread1=threading.Thread(target=T1_job,name='T1')
    thread2 = threading.Thread(target=T2_job,name='T2')
    thread1.start()
    thread2.start()
    thread2.join()
    thread1.join()
    print('all done\n')
   
if __name__=='__main__':#判断是否为主模块,如果是,则运行main()函数
    main()

If there is no join in the above code

 	thread2.join()
    thread1.join()

The output of the running result:

T1 start
T2 start
all done

T2 finish
>>> 
T1 finishi

Output only when thread1.join():

T1 start
T2 start


T2 finish

T1 finishi

all done

Output only when thread2.join():

T1 start
T2 start


T2 finish

all done

>>> T1 finishi

Output when both threads have join:

T1 start
T2 start


T2 finish

T1 finishi

all done

4 Queue

Python's Queue module provides synchronous, thread-safe queue classes, including FIFO (first-in-first-out) queue Queue, LIFO (last-in-first-out) queue LifoQueue, and priority queue PriorityQueue. These queues implement lock primitives and can be used directly in multiple threads. Queues can be used to achieve synchronization between threads .

By creating a Queue instance, we can share this instance among multiple threads, and use the put() method to add data to the queue and use the get() method to get data from the queue.

import threading
import time
from queue import Queue

def job(l,q):
    for i in range(len(l)):
        l[i]=l[i]**2
    q.put(l)        #线程是无法返回一个值的 

def multithreading():
    q = Queue()
    threads = []
    data= [[1,2,3],[3,4,5],[4,5,6],[5,6,7]]
    for i in range(4):
        t = threading.Thread(target=job,args=(data[i],q))#job后没有()
        t.start()
        threads.append(t)
    for thread in threads:
        thread.join()
    results = []
    for _ in range(4):
        results.append(q.get())
    print(results)
        
if __name__=='__main__':
    multithreading()

In Python, we can create threads using the threading module. When we create a thread, we can use the target parameter to specify the function to be executed by the thread. In this example, the objective function is job .

In addition to the target parameter, threading.Thread() also provides an args parameter. args is a tuple which can contain arguments passed to the objective function. In this example, the args parameter contains two values: data[i] and q. This means that when starting a thread, the target function job will be called, passing data[i] and q as parameters to it .

In other words, the role of args is to pass arguments to the target function. This allows us to easily pass multiple parameters to a function without having to hardcode those parameters inside the function.

operation result:

[[1, 4, 9], [9, 16, 25], [16, 25, 36], [25, 36, 49]]

5 Not necessarily efficient GIL

Efficiency comparison experiment of single-thread, multi-thread and multi-process in Python
insert image description here
GIL (Global Interpreter Lock) is an important concept in Python, which is a thread synchronization mechanism. In the Python interpreter, each thread needs to acquire the GIL to execute, that is, only one thread at a time can execute Python bytecode in the interpreter. The GIL is a mutex that ensures that only one thread can access Python objects and execute Python bytecode at a time. This mechanism avoids race conditions and data inconsistencies when multiple threads modify Python objects and bytecodes at the same time.

The presence of the GIL has the following effects on Python's multithreaded applications:

  1. Limiting the utilization of multi-core CPUs: Due to the existence of GIL, multiple threads cannot execute Python bytecode at the same time, which means that multi-threaded applications in Python cannot utilize multiple CPU cores. Even if multiple threads are used in a multi-threaded application, only one thread can use the CPU, and other threads can only wait for the release of the GIL.

  2. Small impact on I/O-intensive applications: I/O-intensive applications need to wait for external resources (such as network I/O or disk I/O) during execution, so in these applications, the impact of the GIL is relatively smaller. Because while one thread is waiting for I/O, other threads can acquire the GIL and execute Python code.

  3. High impact on CPU-intensive applications: CPU-intensive applications require a lot of CPU resources, so in these applications, the impact of the GIL is relatively large. Because when one thread is performing CPU-intensive tasks, other threads must wait for the release of the GIL, which can cause performance bottlenecks.

It should be noted that the GIL only works on interpreter-level Python code. For some extension modules in Python (such as numpy and pandas), they use code written in C language, which can be executed without the restriction of GIL, so they can fully utilize multiple CPU cores.

import threading
from queue import Queue
import copy
import time

def job(l, q):
    res = sum(l)
    q.put(res)

def multithreading(l):
    q = Queue()
    threads = []
    for i in range(4):
        t = threading.Thread(target=job, args=(copy.copy(l), q), name='T%i' % i)
        t.start()
        threads.append(t)
    [t.join() for t in threads]
    total = 0
    for _ in range(4):
        total += q.get()
    print(total)

def normal(l):
    total = sum(l)
    print(total)

if __name__ == '__main__':
    l = list(range(1000000))
    s_t = time.time()
    normal(l*4)
    print('normal: ',time.time()-s_t)
    s_t = time.time()
    multithreading(l)
    print('multithreading: ', time.time()-s_t)

insert image description here

6 lock lock

When no lock:

import threading

def job1():
    global A, lock
    for i in range(10):
        A += 1
        print('job1', A)

def job2():
    global A, lock
    for i in range(10):
        A += 10
        print('job2', A)
   
if __name__ == '__main__':
    A = 0
    t1 = threading.Thread(target=job1)
    t2 = threading.Thread(target=job2)
    t1.start()
    t2.start()
    t1.join()
    t2.join()

The running result is very confusing:
in fact, it is used alternately because A is used.
0+1=1, 1+10 is 11, output 111,
11+1=12, 12+10=22, output 1222
+1, +10 run alternately

job1job2  111

job1job2  1222

job1job2  2333

job1job2  3444

job1job2  4555

job1job2  5666

job1job2  6777

job1job2  7888

job1job2  8999

job1job2  100110

After being modified to A, B said

import threading

def job1():
    global A, lock
    for i in range(10):
        A += 1
        print('job1 %s '% A)

def job2():
    global B, lock
    for i in range(10):
        B += 10
        print('job2 %s '% B)
   
if __name__ == '__main__':
    A = 0
    B = 0
    t1 = threading.Thread(target=job1)
    t2 = threading.Thread(target=job2)
    t1.start()
    t2.start()
    t1.join()
    t2.join()

operation result:

job1 1 job2 10 

job1 2 job2 20 

job1 3 job2 30 

job1 4 job2 40 

job1 5 job2 50 

job1 6 job2 60 

job1 7 job2 70 

job1 8 job2 80 

job1 9 job2 90 

job1 10 job2 100

When there is a lock:
use lock.acquire() and lock.release() to indicate the beginning and end of the lock.

import threading

def job1():
    global A, lock
    lock.acquire()
    for i in range(10):
        A += 1
        print('job1', A)
    lock.release()

def job2():
    global A, lock
    lock.acquire()
    for i in range(10):
        A += 10
        print('job2', A)
    lock.release()

if __name__ == '__main__':
    lock = threading.Lock()
    A = 0
    t1 = threading.Thread(target=job1)
    t2 = threading.Thread(target=job2)
    t1.start()
    t2.start()
    t1.join()
    t2.join()

operation result:

job1 1
job1 2
job1 3
job1 4
job1 5
job1 6
job1 7
job1 8
job1 9
job1 10
job2 20
job2 30
job2 40
job2 50
job2 60
job2 70
job2 80
job2 90
job2 100
job2 110

32 Multiprocessing Unleash Your Multicore Computer's True Potential

Multiprocessing video series

1 What is multiprocessing

In Python, multiprocessing refers to running multiple independent processes at the same time, each process has its own execution space and system resources. Each process can run independently and execute tasks, and multiple tasks can be executed at the same time, thereby achieving parallel processing.

Python's multiprocessing module (multiprocessing) can be used to create and manage multiple processes. Each process has its own process ID, which can be used to identify and control the behavior of the process. The advantage of multi-process is that it can make full use of multi-core CPU and improve the execution efficiency of the program.

In Python, multiple processes can be implemented in various ways, including using the multiprocessing module, using the fork method of the os module to create subprocesses, and using the subprocess module to call other programs, etc. When using multiple processes, you need to pay attention to the communication and synchronization between processes to avoid problems such as data competition and deadlock.

2 create process

import multiprocessing as mp

def job(a,b):
    print('aaaa')

if __name__=='__main__':
    p1 = mp.Process(target=job,args=(1,2))
    p1.start()
    p1.join()

3 queue

In this example, the job is calculated twice and then added

import multiprocessing as mp

def job(q):
    res = 0
    for i in range(1000):
        res += i+i**2+i**3
    q.put(res) # queue

if __name__ == '__main__':
    q = mp.Queue()
    p1 = mp.Process(target=job, args=(q,))
    p2 = mp.Process(target=job, args=(q,))
    p1.start()
    p2.start()
    p1.join()
    p2.join()
    res1 = q.get()
    res2 = q.get()
    print(res1+res2)

4 Efficiency comparison between multithreading and multiprocessing

In Python, the time.time() function returns the current timestamp, which is the number of seconds since midnight January 1, 1970 (epoch time in UTC/GMT) to the current time. It returns a floating point number, usually expressed as a fraction of seconds, eg: 1617217878.8957865. This function is often used to calculate the execution time of a program.
The subtraction in the example is to obtain the running time of the program.

import multiprocessing as mp
import threading as td
import time

def job(q):
    res = 0
    for i in range(1000000):
        res += i+i**2+i**3
    q.put(res) # queue

def multicore():
    q = mp.Queue()
    p1 = mp.Process(target=job, args=(q,))
    p2 = mp.Process(target=job, args=(q,))
    p1.start()
    p2.start()
    p1.join()
    p2.join()
    res1 = q.get()
    res2 = q.get()
    print('multicore:' , res1+res2)

def normal():
    res = 0
    for _ in range(2):
        for i in range(1000000):
            res += i+i**2+i**3
    print('normal:', res)

def multithread():
    q = mp.Queue()
    t1 = td.Thread(target=job, args=(q,))
    t2 = td.Thread(target=job, args=(q,))
    t1.start()
    t2.start()
    t1.join()
    t2.join()
    res1 = q.get()
    res2 = q.get()
    print('multithread:', res1+res2)

if __name__ == '__main__':
    st = time.time()
    normal()
    st1= time.time()
    print('normal time:', st1 - st)
    multithread()
    st2 = time.time()
    print('multithread time:', st2 - st1)
    multicore()
    print('multicore time:', time.time()-st2)

My computer running results:

normal: 499999666667166666000000
normal time: 1.3881876468658447
multithread: 499999666667166666000000
multithread time: 1.3638417720794678
multicore: 499999666667166666000000
multicore time: 0.8919181823730469

5 process pool pool

import multiprocessing as mp

def job(x):
    return x*x

def multicore():
    pool = mp.Pool(processes=2)
    res = pool.map(job, range(10))
    print(res)
    res = pool.apply_async(job, (2,))
    print(res.get())
    multi_res =[pool.apply_async(job, (i,)) for i in range(10)]
    print([res.get() for res in multi_res])

if __name__ == '__main__':
    multicore()

6 shared memory shared memory

multiprocessing.Value() is a function provided by the multiprocessing module in Python. Its function is to create a shared variable that can be accessed and modified by multiple processes at the same time.

Two parameters need to be passed in the parentheses of the function, which are the type and initial value of the shared variable. The type of shared variable can be the character representation of basic data types such as 'c', 'b', 'h', 'i', 'l', 'f' or 'd', respectively representing char, bool, short, int , shared variables of type long, float and double. The initial value is the initial value of the shared variable, which can be any legal value of the corresponding type.

For example, you can create an integer shared variable x with an initial value of 0 by the following code:

from multiprocessing import Value

x = Value('i', 0)

In this way, the value of the shared variable can be accessed and modified through x.value in multiple processes, and the modification operations of the shared variable by multiple processes are synchronized, and there will be no data competition problem .

7 lock lock

import multiprocessing as mp
import time

def job(v, num, l):
    l.acquire()
    for _ in range(10):
        time.sleep(0.1)
        v.value += num
        print(v.value)
    l.release()

def multicore():
    l = mp.Lock()
    v = mp.Value('i', 0)
    p1 = mp.Process(target=job, args=(v, 1, l))
    p2 = mp.Process(target=job, args=(v, 3, l))
    p1.start()
    p2.start()
    p1.join()
    p2.join()

if __name__ == '__main__':
    multicore()

<error: no output>

33 Tkinter makes a simple window Python GUI

1 What is Tkinter

Tkinter is a module for windowing and windowing in python . The Tkinter module ("Tk interface") is an interface to Python's standard Tk GUI toolkit. As a python-specific GUI interface, it is an image window. Tkinter is an editable GUI interface that comes with python. We can use GUI to realize many intuitive functions. For example, if we want to develop a calculator, if it is just a program input and output The window is useless for user experience. It is necessary to develop a small graphical window.

For those with a little GUI programming experience, Python's Tkinter interface library is very simple. There are many GUI libraries for python. Tkinter is the easiest choice. The second is the built-in library, which can be used at any time without downloading and installing. The third is to start from the demand. Python is a scripting language and a glue language. Will use it to develop complex desktop applications, it does not have the advantage in this regard, using Python, you can use it as a flexible tool, rather than as the main development language, then in the work, you need to make a small tool, for sure It needs an interface, not only for your own use, but also for sharing with others. Under this requirement, Tkinter is competent enough!

2 Label & Button label and button

import tkinter as tk

window = tk.Tk()
window.title('my window')
window.geometry('200x100')

var = tk.StringVar()
l = tk.Label(window, textvariable=var, bg='green', font=('Arial', 12), width=15,
             height=2)
#l = tk.Label(window, text='OMG! this is TK!', bg='green', font=('Arial', 12), width=15, height=2)
l.pack()

on_hit = False
def hit_me():
    global on_hit
    if on_hit == False:
        on_hit = True
        var.set('you hit me')
    else:
        on_hit = False
        var.set('')

b = tk.Button(window, text='hit me', width=15,
              height=2, command=hit_me)
b.pack()


window.mainloop()

3 Entry & Text input, text box

import tkinter as tk

window = tk.Tk()
window.title('my window')
window.geometry('200x200')
# e = tk.Entry(window, show="*")
e = tk.Entry(window, show="1")
e.pack()

def insert_point():
    var = e.get()
    t.insert('insert', var)
def insert_end():
    var = e.get()
    # t.insert('end', var)
    t.insert(2.2, var)

b1 = tk.Button(window, text='insert point', width=15,
              height=2, command=insert_point)
b1.pack()
b2 = tk.Button(window, text='insert end',
               command=insert_end)
b2.pack()
t = tk.Text(window, height=2)
t.pack()

window.mainloop()

4 Listbox widget

import tkinter as tk

window = tk.Tk()
window.title('my window')
window.geometry('200x200')

var1 = tk.StringVar()
l = tk.Label(window, bg='yellow', width=4, textvariable=var1)
l.pack()

def print_selection():
    value = lb.get(lb.curselection())
    var1.set(value)

b1 = tk.Button(window, text='print selection', width=15,
              height=2, command=print_selection)
b1.pack()

var2 = tk.StringVar()
var2.set((11,22,33,44))
lb = tk.Listbox(window, listvariable=var2)
list_items = [1,2,3,4]
for item in list_items:
    lb.insert('end', item)
lb.insert(1, 'first')
lb.insert(2, 'second')
lb.delete(2)
lb.pack()

window.mainloop()

5 Radiobutton selection button

import tkinter as tk

window = tk.Tk()
window.title('my window')
window.geometry('200x200')

var = tk.StringVar()
l = tk.Label(window, bg='yellow', width=20, text='empty')
l.pack()

def print_selection():
    l.config(text='you have selected ' + var.get())

r1 = tk.Radiobutton(window, text='Option A',
                    variable=var, value='A',
                    command=print_selection)
r1.pack()
r2 = tk.Radiobutton(window, text='Option B',
                    variable=var, value='B',
                    command=print_selection)
r2.pack()
r3 = tk.Radiobutton(window, text='Option C',
                    variable=var, value='C',
                    command=print_selection)
r3.pack()


window.mainloop()

6 Scale scale

import tkinter as tk

window = tk.Tk()
window.title('my window')
window.geometry('200x200')

l = tk.Label(window, bg='yellow', width=20, text='empty')
l.pack()

def print_selection(v):
    l.config(text='you have selected ' + v)

s = tk.Scale(window, label='try me', from_=5, to=11, orient=tk.HORIZONTAL,
             length=200, showvalue=0, tickinterval=2, resolution=0.01, command=print_selection)
s.pack()

window.mainloop()

7 Checkbutton option

import tkinter as tk

window = tk.Tk()
window.title('my window')
window.geometry('200x200')

l = tk.Label(window, bg='yellow', width=20, text='empty')
l.pack()

def print_selection():
    if (var1.get() == 1) & (var2.get() == 0):
        l.config(text='I love only Python ')
    elif (var1.get() == 0) & (var2.get() == 1):
        l.config(text='I love only C++')
    elif (var1.get() == 0) & (var2.get() == 0):
        l.config(text='I do not love either')
    else:
        l.config(text='I love both')

var1 = tk.IntVar()
var2 = tk.IntVar()
c1 = tk.Checkbutton(window, text='Python', variable=var1, onvalue=1, offvalue=0,
                    command=print_selection)
c2 = tk.Checkbutton(window, text='C++', variable=var2, onvalue=1, offvalue=0,
                    command=print_selection)
c1.pack()
c2.pack()


window.mainloop()

8 Canvas Canvas

The picture named ins.gif is placed in the same folder.
insert image description here

import tkinter as tk

window = tk.Tk()
window.title('my window')
window.geometry('200x200')

canvas = tk.Canvas(window, bg='blue', height=100, width=200)
image_file = tk.PhotoImage(file='ins.gif')
image = canvas.create_image(10, 10, anchor='nw', image=image_file)
x0, y0, x1, y1= 50, 50, 80, 80
line = canvas.create_line(x0, y0, x1, y1)
oval = canvas.create_oval(x0, y0, x1, y1, fill='red')
arc = canvas.create_arc(x0+30, y0+30, x1+30, y1+30, start=0, extent=180)
rect = canvas.create_rectangle(100, 30, 100+20, 30+20)
canvas.pack()

def moveit():
    canvas.move(rect, 0, 2)

b = tk.Button(window, text='move', command=moveit).pack()

window.mainloop()

9 Menubar menu

import tkinter as tk

window = tk.Tk()
window.title('my window')
window.geometry('200x200')

l = tk.Label(window, text='', bg='yellow')
l.pack()
counter = 0
def do_job():
    global counter
    l.config(text='do '+ str(counter))
    counter+=1

menubar = tk.Menu(window)
filemenu = tk.Menu(menubar, tearoff=0)
menubar.add_cascade(label='File', menu=filemenu)
filemenu.add_command(label='New', command=do_job)
filemenu.add_command(label='Open', command=do_job)
filemenu.add_command(label='Save', command=do_job)
filemenu.add_separator()
filemenu.add_command(label='Exit', command=window.quit)

editmenu = tk.Menu(menubar, tearoff=0)
menubar.add_cascade(label='Edit', menu=editmenu)
editmenu.add_command(label='Cut', command=do_job)
editmenu.add_command(label='Copy', command=do_job)
editmenu.add_command(label='Paste', command=do_job)

submenu = tk.Menu(filemenu)
filemenu.add_cascade(label='Import', menu=submenu, underline=0)
submenu.add_command(label="Submenu1", command=do_job)

window.config(menu=menubar)

window.mainloop()

10 Frame frame

import tkinter as tk

window = tk.Tk()
window.title('my window')
window.geometry('200x200')
tk.Label(window, text='on the window').pack()

frm = tk.Frame(window)
frm.pack()
frm_l = tk.Frame(frm, )
frm_r = tk.Frame(frm)
frm_l.pack(side='left')
frm_r.pack(side='right')

tk.Label(frm_l, text='on the frm_l1').pack()
tk.Label(frm_l, text='on the frm_l2').pack()
tk.Label(frm_r, text='on the frm_r1').pack()
window.mainloop()

11 messagebox pop-up window

import tkinter as tk
import tkinter.messagebox

window = tk.Tk()
window.title('my window')
window.geometry('200x200')

def hit_me():
    #tk.messagebox.showinfo(title='Hi', message='hahahaha')   # return 'ok'
    #tk.messagebox.showwarning(title='Hi', message='nononono')   # return 'ok'
    #tk.messagebox.showerror(title='Hi', message='No!! never')   # return 'ok'
    #print(tk.messagebox.askquestion(title='Hi', message='hahahaha'))   # return 'yes' , 'no'
    #print(tk.messagebox.askyesno(title='Hi', message='hahahaha'))   # return True, False
    print(tk.messagebox.asktrycancel(title='Hi', message='hahahaha'))   # return True, False
    print(tk.messagebox.askokcancel(title='Hi', message='hahahaha'))   # return True, False
    print(tk.messagebox.askyesnocancel(title="Hi", message="haha"))     # return, True, False, None

tk.Button(window, text='hit me', command=hit_me).pack()
window.mainloop()

12 pack grid place placement

import tkinter as tk

window = tk.Tk()
window.geometry('200x200')

#canvas = tk.Canvas(window, height=150, width=500)
#canvas.grid(row=1, column=1)
#image_file = tk.PhotoImage(file='welcome.gif')
#image = canvas.create_image(0, 0, anchor='nw', image=image_file)

#tk.Label(window, text='1').pack(side='top')
#tk.Label(window, text='1').pack(side='bottom')
#tk.Label(window, text='1').pack(side='left')
#tk.Label(window, text='1').pack(side='right')

#for i in range(4):
    #for j in range(3):
        #tk.Label(window, text=1).grid(row=i, column=j, padx=10, pady=10)

tk.Label(window, text=1).place(x=20, y=10, anchor='nw')

window.mainloop()

13 Example 1 login window

The image named welcome.gif is placed in the same file.
insert image description here

import tkinter as tk

window = tk.Tk()
window.title('Welcome to Mofan Python')
window.geometry('450x300')

# welcome image
canvas = tk.Canvas(window, height=200, width=500)
image_file = tk.PhotoImage(file='welcome.gif')
image = canvas.create_image(0,0, anchor='nw', image=image_file)
canvas.pack(side='top')

# user information
tk.Label(window, text='User name: ').place(x=50, y= 150)
tk.Label(window, text='Password: ').place(x=50, y= 190)

var_usr_name = tk.StringVar()
var_usr_name.set('[email protected]')
entry_usr_name = tk.Entry(window, textvariable=var_usr_name)
entry_usr_name.place(x=160, y=150)
var_usr_pwd = tk.StringVar()
entry_usr_pwd = tk.Entry(window, textvariable=var_usr_pwd, show='*')
entry_usr_pwd.place(x=160, y=190)

def usr_login():
    pass
def usr_sign_up():
    pass

# login and sign up button
btn_login = tk.Button(window, text='Login', command=usr_login)
btn_login.place(x=170, y=230)
btn_sign_up = tk.Button(window, text='Sign up', command=usr_sign_up)
btn_sign_up.place(x=270, y=230)

window.mainloop()

14 Example 1 login window

import tkinter as tk
import pickle

window = tk.Tk()
window.title('Welcome to Mofan Python')
window.geometry('450x300')

# welcome image
canvas = tk.Canvas(window, height=200, width=500)
image_file = tk.PhotoImage(file='welcome.gif')
image = canvas.create_image(0,0, anchor='nw', image=image_file)
canvas.pack(side='top')

# user information
tk.Label(window, text='User name: ').place(x=50, y= 150)
tk.Label(window, text='Password: ').place(x=50, y= 190)

var_usr_name = tk.StringVar()
var_usr_name.set('[email protected]')
entry_usr_name = tk.Entry(window, textvariable=var_usr_name)
entry_usr_name.place(x=160, y=150)
var_usr_pwd = tk.StringVar()
entry_usr_pwd = tk.Entry(window, textvariable=var_usr_pwd, show='*')
entry_usr_pwd.place(x=160, y=190)

def usr_login():
    usr_name = var_usr_name.get()
    usr_pwd = var_usr_pwd.get()
    try:
        with open('usrs_info.pickle', 'rb') as usr_file:
            usrs_info = pickle.load(usr_file)
    except FileNotFoundError:
        with open('usrs_info.pickle', 'wb') as usr_file:
            usrs_info = {
    
    'admin': 'admin'}
            pickle.dump(usrs_info, usr_file)
    if usr_name in usrs_info:
        if usr_pwd == usrs_info[usr_name]:
            tk.messagebox.showinfo(title='Welcome', message='How are you? ' + usr_name)
        else:
            tk.messagebox.showerror(message='Error, your password is wrong, try again.')
    else:
        is_sign_up = tk.messagebox.askyesno('Welcome',
                               'You have not sign up yet. Sign up today?')
        if is_sign_up:
            usr_sign_up()

def usr_sign_up():
    pass

# login and sign up button
btn_login = tk.Button(window, text='Login', command=usr_login)
btn_login.place(x=170, y=230)
btn_sign_up = tk.Button(window, text='Sign up', command=usr_sign_up)
btn_sign_up.place(x=270, y=230)

window.mainloop()

15 Example 1 login window

import tkinter as tk
from tkinter import messagebox  # import this to fix messagebox error
import pickle

window = tk.Tk()
window.title('Welcome to Mofan Python')
window.geometry('450x300')

# welcome image
canvas = tk.Canvas(window, height=200, width=500)
image_file = tk.PhotoImage(file='welcome.gif')
image = canvas.create_image(0,0, anchor='nw', image=image_file)
canvas.pack(side='top')

# user information
tk.Label(window, text='User name: ').place(x=50, y= 150)
tk.Label(window, text='Password: ').place(x=50, y= 190)

var_usr_name = tk.StringVar()
var_usr_name.set('[email protected]')
entry_usr_name = tk.Entry(window, textvariable=var_usr_name)
entry_usr_name.place(x=160, y=150)
var_usr_pwd = tk.StringVar()
entry_usr_pwd = tk.Entry(window, textvariable=var_usr_pwd, show='*')
entry_usr_pwd.place(x=160, y=190)

def usr_login():
    usr_name = var_usr_name.get()
    usr_pwd = var_usr_pwd.get()
    try:
        with open('usrs_info.pickle', 'rb') as usr_file:
            usrs_info = pickle.load(usr_file)
    except FileNotFoundError:
        with open('usrs_info.pickle', 'wb') as usr_file:
            usrs_info = {
    
    'admin': 'admin'}
            pickle.dump(usrs_info, usr_file)
    if usr_name in usrs_info:
        if usr_pwd == usrs_info[usr_name]:
            tk.messagebox.showinfo(title='Welcome', message='How are you? ' + usr_name)
        else:
            tk.messagebox.showerror(message='Error, your password is wrong, try again.')
    else:
        is_sign_up = tk.messagebox.askyesno('Welcome',
                               'You have not signed up yet. Sign up today?')
        if is_sign_up:
            usr_sign_up()

def usr_sign_up():
    def sign_to_Mofan_Python():
        np = new_pwd.get()
        npf = new_pwd_confirm.get()
        nn = new_name.get()
        with open('usrs_info.pickle', 'rb') as usr_file:
            exist_usr_info = pickle.load(usr_file)
        if np != npf:
            tk.messagebox.showerror('Error', 'Password and confirm password must be the same!')
        elif nn in exist_usr_info:
            tk.messagebox.showerror('Error', 'The user has already signed up!')
        else:
            exist_usr_info[nn] = np
            with open('usrs_info.pickle', 'wb') as usr_file:
                pickle.dump(exist_usr_info, usr_file)
            tk.messagebox.showinfo('Welcome', 'You have successfully signed up!')
            window_sign_up.destroy()
    window_sign_up = tk.Toplevel(window)
    window_sign_up.geometry('350x200')
    window_sign_up.title('Sign up window')

    new_name = tk.StringVar()
    new_name.set('[email protected]')
    tk.Label(window_sign_up, text='User name: ').place(x=10, y= 10)
    entry_new_name = tk.Entry(window_sign_up, textvariable=new_name)
    entry_new_name.place(x=150, y=10)

    new_pwd = tk.StringVar()
    tk.Label(window_sign_up, text='Password: ').place(x=10, y=50)
    entry_usr_pwd = tk.Entry(window_sign_up, textvariable=new_pwd, show='*')
    entry_usr_pwd.place(x=150, y=50)

    new_pwd_confirm = tk.StringVar()
    tk.Label(window_sign_up, text='Confirm password: ').place(x=10, y= 90)
    entry_usr_pwd_confirm = tk.Entry(window_sign_up, textvariable=new_pwd_confirm, show='*')
    entry_usr_pwd_confirm.place(x=150, y=90)

    btn_comfirm_sign_up = tk.Button(window_sign_up, text='Sign up', command=sign_to_Mofan_Python)
    btn_comfirm_sign_up.place(x=150, y=130)

# login and sign up button
btn_login = tk.Button(window, text='Login', command=usr_login)
btn_login.place(x=170, y=230)
btn_sign_up = tk.Button(window, text='Sign up', command=usr_sign_up)
btn_sign_up.place(x=270, y=230)

window.mainloop()

Guess you like

Origin blog.csdn.net/weixin_48412658/article/details/129753519