News from this site

 Rental advertising space, please contact the webmaster if you need cooperation


+focus
focused

classification  

no classification

tag  

no tag

date  

no datas

Python romance 520 confession code

posted on 2023-05-21 17:07     read(1052)     comment(0)     like(23)     collect(5)


Table of contents

foreword

confession interface

beating heart

floating hearts

Full screen confession code


foreword

520 is May 20 every year. Because the number "520" sounds similar to "I love you", it is used by many young people as a festival to express love. This festival originated from Chinese Internet culture and gradually spread to other countries and regions. On this day, couples usually celebrate love by giving each other gifts, posting emoticons, or holding romantic activities. Come and claim the romance exclusive to programmers !

confession interface

An irresistible confession interface!

programming 

  1. import tkinter as tk
  2. import tkinter.messagebox
  3. root = tk.Tk()
  4. root.title('❤')
  5. root.resizable(0, 0)
  6. root.wm_attributes("-toolwindow", 1)
  7. screenwidth = root.winfo_screenwidth()
  8. screenheight = root.winfo_screenheight()
  9. widths = 300
  10. heights = 100
  11. x = (screenwidth - widths) / 2
  12. y = (screenheight - heights) / 2
  13. root.geometry('%dx%d+%d+%d' % (widths, heights, x, y)) # 设置在屏幕中居中显示
  14. tk.Label(root, text='亲爱的,做我女朋友好吗?', width=37, font=('宋体', 12)).place(x=0, y=10)
  15. def OK(): # 同意按钮
  16. root.destroy()
  17. # 同意后显示漂浮爱心
  18. def NO(): # 拒绝按钮,拒绝不会退出,必须同意才可以退出哦~
  19. tk.messagebox.showwarning('❤', '再给你一次机会!')
  20. def closeWindow():
  21. tk.messagebox.showwarning('❤', '逃避是没有用的哦')
  22. tk.Button(root, text='好哦', width=5, height=1, command=OK).place(x=80, y=50)
  23. tk.Button(root, text='不要', width=5, height=1, command=NO).place(x=160, y=50)
  24. root.protocol('WM_DELETE_WINDOW', closeWindow) # 绑定退出事件
  25. root.mainloop()

This code uses Python's Tkinter library to create the GUI interface. In this program, there are several main components, as follows:

  1. tk.Tk(): create a main window;

  2. root.title(): Set the title of the window, here it is set to '❤';

  3. root.resizable(0,0): The window size cannot be adjusted, that is, the user is prohibited from manually adjusting the window size;

  4. root.wm_attributes(“-toolwindow”, 1): Set the window as a tool window, that is, there are no maximize, minimize and close buttons;

  5. root.geometry(): Set the size and position of the window, which is set to be displayed in the center of the screen;

  6. tk.Label(): Create a label for displaying prompt information, here is "Honey, can you be my girlfriend?";

  7. tk.Button(): Create two buttons for agreeing and rejecting respectively, and bind two functions of OK() and NO() respectively;

  8. root.protocol(): Bind the exit event, if the user tries to close the window directly, a warning window will pop up to remind that evasion is useless;

  9. root.mainloop(): The main loop of the program, keeping the window open.

In general, this is a confession program written in Python's Tkinter library. Its main function is to display a window asking the user if he wants to be his girlfriend, and provides two buttons of "Yes" and "Don't" for the user choose. If the user chooses to agree, the window will close, and a floating heart effect will appear; if the user chooses not to agree, a warning window will pop up to remind you to give another chance. At the same time, if the user tries to close this window directly, a warning window will pop up to remind that evasion is useless. 

beating heart

The beating love that exploded last year!

main love class 

  1. class Heart:
  2. def __init__(self, generate_frame=20):
  3. self._points = set() # 原始爱心坐标集合
  4. self._edge_diffusion_points = set() # 边缘扩散效果点坐标集合
  5. self._center_diffusion_points = set() # 中心扩散效果点坐标集合
  6. self.all_points = {} # 每帧动态点坐标
  7. self.build(2000)
  8. self.random_halo = 1000
  9. self.generate_frame = generate_frame
  10. for frame in range(generate_frame):
  11. self.calc(frame)
  12. def build(self, number):
  13. for _ in range(number):
  14. t = random.uniform(0, 2 * pi)
  15. x, y = heart_function(t)
  16. self._points.add((x, y))
  17. for _x, _y in list(self._points):
  18. for _ in range(3):
  19. x, y = scatter_inside(_x, _y, 0.05)
  20. self._edge_diffusion_points.add((x, y))
  21. point_list = list(self._points)
  22. for _ in range(4000):
  23. x, y = random.choice(point_list)
  24. x, y = scatter_inside(x, y, 0.17)
  25. self._center_diffusion_points.add((x, y))
  26. @staticmethod
  27. def calc_position(x, y, ratio):
  28. force = 1 / (((x - heartx) ** 2 + (y - hearty) ** 2) ** 0.520) # 魔法参数
  29. dx = ratio * force * (x - heartx) + random.randint(-1, 1)
  30. dy = ratio * force * (y - hearty) + random.randint(-1, 1)
  31. return x - dx, y - dy
  32. def calc(self, generate_frame):
  33. ratio = 10 * curve(generate_frame / 10 * pi) # 圆滑的周期的缩放比例
  34. halo_radius = int(4 + 6 * (1 + curve(generate_frame / 10 * pi)))
  35. halo_number = int(3000 + 4000 * abs(curve(generate_frame / 10 * pi) ** 2))
  36. all_points = []
  37. heart_halo_point = set()
  38. for _ in range(halo_number):
  39. t = random.uniform(0, 2 * pi)
  40. x, y = heart_function(t, shrink_ratio=11.6)
  41. x, y = shrink(x, y, halo_radius)
  42. if (x, y) not in heart_halo_point:
  43. heart_halo_point.add((x, y))
  44. x += random.randint(-14, 14)
  45. y += random.randint(-14, 14)
  46. size = random.choice((1, 2, 2))
  47. all_points.append((x, y, size))
  48. for x, y in self._points:
  49. x, y = self.calc_position(x, y, ratio)
  50. size = random.randint(1, 3)
  51. all_points.append((x, y, size))
  52. for x, y in self._edge_diffusion_points:
  53. x, y = self.calc_position(x, y, ratio)
  54. size = random.randint(1, 2)
  55. all_points.append((x, y, size))
  56. for x, y in self._center_diffusion_points:
  57. x, y = self.calc_position(x, y, ratio)
  58. size = random.randint(1, 2)
  59. all_points.append((x, y, size))
  60. self.all_points[generate_frame] = all_points
  61. def render(self, render_canvas, render_frame):
  62. for x, y, size in self.all_points[render_frame % self.generate_frame]:
  63. render_canvas.create_rectangle(x, y, x + size, y + size, width=0, fill=heartcolor)

 This part of the code is mainly used to generate a heart shape and display the heart on the screen in a slow flowing manner. A class called Heart is used here to achieve this function. Specifically, this class contains the following methods:

1. __init__(): When the Heart class is initialized, some points are generated to form the original heart shape, and the edge and center heart effects are expanded, and finally stored in the _points, _edge_diffusion_points, _center_diffusion_points collection, in __init__( ) also uses the calc() method to generate and store dynamic point coordinates as the basis for subsequent display;

2. build(): This method randomly generates a coordinate point according to the number passed in, and calculates the scatter point, edge effect point and center effect point generated by this coordinate point, and adds these points to the corresponding in the collection;

3. calc_position(): This method is used to calculate the coordinates of the point of the dynamic effect, x and y are the coordinates of the original love point, and ratio is a scaling factor used to control the speed and direction of the point. The specific implementation method is to calculate the coordinate point offset (dx and dy) according to the magic parameter (force), and subtract the offset from the original coordinate to get the new coordinate;

4. calc(): This method calculates the coordinates of each point after movement, the size and number of positions and other parameters according to the incoming frame number (generate_frame), and generates a set of all_points for subsequent window display;

5. render(): This method is used to generate the effect of window display. According to the incoming canvas render_canvas and frame number render_frame, get the dynamic points (all_points) and use the create_rectangle() method to present each point on the canvas, forming the slow flow effect of love.

In general, this part of the code realizes the core method of the dynamic effect of love. By presenting scattered points, edge effect points and center effect points, the coordinates of dynamic points are calculated, and an intriguing display of love effects is formed through slow changes.

floating hearts

Of course, the floating hearts are also beautiful!

main love class 

  1. class Heart(): #每个爱心(爱心类)
  2. def __init__(self):
  3. self.r = ra.randint(10,15) #爱心的半径
  4. self.x = ra.randint(-1000,1000) #爱心的横坐标
  5. self.y = ra.randint(-500,500) #爱心的纵坐标
  6. self.f = ra.uniform(-3.14,3.14) #爱心左右移动呈正弦函数
  7. self.speed = ra.randint(5,10) #爱心移动速度
  8. self.color = ra.choice(colors) #爱心的颜色
  9. self.outline = 1 #爱心的外框大小(可不要)
  10. def move(self): #爱心移动函数
  11. if self.y <= 500: #当爱心还在画布中时
  12. self.y += self.speed #设置上下移动速度
  13. self.x += self.speed * math.sin(self.f) #设置左右移动速度
  14. self.f += 0.1 #可以理解成标志,改变左右移动的方向
  15. else: #当爱心漂出了画布时,重新生成一个爱心
  16. self.r = ra.randint(10,15)
  17. self.x = ra.randint(-1000,1000)
  18. self.y = -500
  19. self.f = ra.uniform(-3.14,3.14)
  20. self.speed = ra.randint(5,10)
  21. self.color = ra.choice(colors)
  22. self.outline = 1
  23. def draw(self): #画爱心函数,就是用turtle画爱心
  24. t.pensize(self.outline)
  25. t.penup()
  26. t.color(self.color)
  27. t.goto(self.x, self.y)
  28. t.pendown()
  29. t.begin_fill()
  30. t.fillcolor('pink')
  31. t.setheading(120)
  32. t.circle(self.r, 195)
  33. t.fd(self.r * 2.4)
  34. t.lt(90)
  35. t.fd(self.r * 2.4)
  36. t.circle(self.r, 195)
  37. t.end_fill()

This part of the code implements the movement and drawing of each heart. By defining a Heart class, some parameters (such as radius, coordinates, speed, color, etc.) are randomly generated during initialization, and then two methods of moving ( move() ) and drawing ( draw() ) are defined to construct each heart in Dynamic effects in canvas.

In the move() method, first judge whether the love heart exceeds the canvas area, and if so, regenerate a love heart. If it is not exceeded, move up and down according to your own speed, and move left and right with a certain period.

In the draw() method, the heart shape is drawn by the Turtle library. Among them, the circle part is drawn with the circle() method, and the line part is drawn with the fd() and lt() methods. At the same time, the color of the heart, the size of the frame, and the fill color are also set.

By cyclically calling move() and draw() operations on each Heart object, the entire screen will dynamically form a lot of floating hearts. Through the attribute differentiation of each heart and the dispersion of movement trajectories, a more colorful and dynamic effect is formed.

Full screen confession code

Who can refuse the confession codes full of screens!

main function 

  1. def Love():
  2. root=tk.Tk()
  3. width=200
  4. height=50
  5. screenwidth=root.winfo_screenwidth()
  6. screenheight=root.winfo_screenheight()
  7. x=ra.randint(0,screenwidth)
  8. y=ra.randint(0,screenheight)
  9. root.title("❤")
  10. root.geometry("%dx%d+%d+%d"%(width,height,x,y))
  11. tk.Label(root,text='I LOVE YOU!',fg='white',bg='pink',font=("Comic Sans MS",15),width=30,height=5).pack()
  12. root.mainloop()
  13. def Heart():
  14. root=tk.Tk()
  15. screenwidth=root.winfo_screenwidth()
  16. screenheight=root.winfo_screenheight()
  17. width=600
  18. height=400
  19. x=(screenwidth-width)//2
  20. y=(screenheight-height)//2
  21. root.title("❤")
  22. root.geometry("%dx%d+%d+%d"%(screenwidth,screenheight,0,0))
  23. tk.Label(root,text='❤',fg='pink',bg='white',font=("Comic Sans MS",500),width=300,height=20).pack()
  24. root.mainloop()

Two functions Love() and Heart() are defined in this program, realizing a romantic effect of expressing love.

The Love() function implements a pop-up window, the window title is "❤", and the window body is a line of words "I LOVE YOU !". The font color is white and the background color is pink. The position of the window is randomly generated and the size is fixed at 200x50.

The Heart() function implements a screensaver effect, and a very large red love heart will appear on the entire screen. The window title is "❤", the color of the heart is pink, and the background is white. The window size is the full screen size, and the position of the window is aligned with the upper left corner, that is, the heart is drawn from the upper left corner of the window.

In general, these two functions achieve a simple and straightforward romantic effect of expressing love. Through specific interface design and color matching, users can quickly express their feelings to others.



Category of website: technical article > Blog

Author:python98k

link:http://www.pythonblackhole.com/blog/article/25256/162aed1956c069a5fcdc/

source:python black hole net

Please indicate the source for any form of reprinting. If any infringement is discovered, it will be held legally responsible.

23 0
collect article
collected

Comment content: (supports up to 255 characters)