The latest Python romance 520 confession code?

 Preface

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

Confession interface

An irresistible confession interface!

programming  

import tkinter as tk
import tkinter.messagebox
root = tk.Tk()
root.title('❤')
root.resizable(0, 0)
root.wm_attributes("-toolwindow", 1)
screenwidth = root.winfo_screenwidth()
screenheight = root.winfo_screenheight()
widths = 300
heights = 100
x = (screenwidth - widths) / 2
y = (screenheight - heights) / 2
root.geometry('%dx%d+%d+%d' % (widths, heights, x, y))  # 设置在屏幕中居中显示
tk.Label(root, text='亲爱的,做我女朋友好吗?', width=37, font=('宋体', 12)).place(x=0, y=10)
 
 
def OK():  # 同意按钮
    root.destroy()
    # 同意后显示漂浮爱心
 
 
def NO():  # 拒绝按钮,拒绝不会退出,必须同意才可以退出哦~
    tk.messagebox.showwarning('❤', '再给你一次机会!')
 
 
def closeWindow():
    tk.messagebox.showwarning('❤', '逃避是没有用的哦')
 
 
tk.Button(root, text='好哦', width=5, height=1, command=OK).place(x=80, y=50)
tk.Button(root, text='不要', width=5, height=1, command=NO).place(x=160, y=50)
root.protocol('WM_DELETE_WINDOW', closeWindow)  # 绑定退出事件
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 escaping is useless;
  9. root.mainloop(): Main loop of the program, keeping the window from closing.
     

In general, this is a confession program written in Python's Tkinter library. Its main function is to display a window and ask the user if he is willing to be his girlfriend. It provides two buttons for the user: "Okay" and "No". choose. If the user chooses to agree, the window will close and a floating heart effect will appear; if the user chooses to disagree, a warning window will pop up to remind you to give it another chance. At the same time, if the user tries to close this window directly, a warning window will pop up to remind that escaping is useless. 

beating heart

The beating love that exploded last year!

Main love category 

class Heart:
    def __init__(self, generate_frame=20):
        self._points = set()  # 原始爱心坐标集合
        self._edge_diffusion_points = set()  # 边缘扩散效果点坐标集合
        self._center_diffusion_points = set()  # 中心扩散效果点坐标集合
        self.all_points = {}  # 每帧动态点坐标
        self.build(2000)
        self.random_halo = 1000
        self.generate_frame = generate_frame
        for frame in range(generate_frame):
            self.calc(frame)
    def build(self, number):
        for _ in range(number):
            t = random.uniform(0, 2 * pi)
            x, y = heart_function(t)
            self._points.add((x, y))
        for _x, _y in list(self._points):
            for _ in range(3):
                x, y = scatter_inside(_x, _y, 0.05)
                self._edge_diffusion_points.add((x, y))
        point_list = list(self._points)
        for _ in range(4000):
            x, y = random.choice(point_list)
            x, y = scatter_inside(x, y, 0.17)
            self._center_diffusion_points.add((x, y))
    @staticmethod
    def calc_position(x, y, ratio):
        force = 1 / (((x - heartx) ** 2 + (y - hearty) ** 2) ** 0.520)  # 魔法参数
        dx = ratio * force * (x - heartx) + random.randint(-1, 1)
        dy = ratio * force * (y - hearty) + random.randint(-1, 1)
        return x - dx, y - dy
    def calc(self, generate_frame):
        ratio = 10 * curve(generate_frame / 10 * pi)  # 圆滑的周期的缩放比例
        halo_radius = int(4 + 6 * (1 + curve(generate_frame / 10 * pi)))
        halo_number = int(3000 + 4000 * abs(curve(generate_frame / 10 * pi) ** 2))
        all_points = []
        heart_halo_point = set()
        for _ in range(halo_number):
            t = random.uniform(0, 2 * pi)
            x, y = heart_function(t, shrink_ratio=11.6)
            x, y = shrink(x, y, halo_radius)
            if (x, y) not in heart_halo_point:
                heart_halo_point.add((x, y))
                x += random.randint(-14, 14)
                y += random.randint(-14, 14)
                size = random.choice((1, 2, 2))
                all_points.append((x, y, size))
        for x, y in self._points:
            x, y = self.calc_position(x, y, ratio)
            size = random.randint(1, 3)
            all_points.append((x, y, size))
        for x, y in self._edge_diffusion_points:
            x, y = self.calc_position(x, y, ratio)
            size = random.randint(1, 2)
            all_points.append((x, y, size))
        for x, y in self._center_diffusion_points:
            x, y = self.calc_position(x, y, ratio)
            size = random.randint(1, 2)
            all_points.append((x, y, size))
        self.all_points[generate_frame] = all_points
    def render(self, render_canvas, render_frame):
        for x, y, size in self.all_points[render_frame % self.generate_frame]:
            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 love effects at the edge and center are expanded, and finally stored in the _points, _edge_diffusion_points, _center_diffusion_points collection, in __init__() The calc() method is also used to generate and store dynamic point coordinates as the basis for subsequent display;
  2. build(): This method randomly generates a coordinate point based on the number passed in, and calculates the scatter points, edge effect points and center effect points generated by this coordinate point, and adds these points to the corresponding set. ;
  3. calc_position(): This method is used to calculate the coordinates of the dynamic effect point. x and y are the original love point coordinates, and ratio is a scaling ratio used to control the movement speed and direction of the point. The specific implementation method is to calculate the offset of the coordinate point (dx and dy) based on the magic parameter (force), and then subtract the offset from the original coordinate to obtain the new coordinate;
  4. calc(): This method calculates the coordinates of each point after movement, the size and number of positions and other parameters based on the frame number passed in (generate_frame), and generates an all_points collection 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, dynamic points (all_points) are obtained and each point is presented on the canvas using the create_rectangle() method, forming a slow flowing effect of love.
     

In general, this part of the code implements the core method of the dynamic effect of love. By presenting scatter points, edge effect points and center effect points, and calculating the coordinates of the dynamic points, an intriguing display of the love effect is formed through slow changes.

floating hearts

Of course, the floating hearts are also beautiful!

Main love category 

class Heart():    #每个爱心(爱心类)
    def __init__(self):
        self.r = ra.randint(10,15)        #爱心的半径
        self.x = ra.randint(-1000,1000)   #爱心的横坐标
        self.y = ra.randint(-500,500)     #爱心的纵坐标
        self.f = ra.uniform(-3.14,3.14)   #爱心左右移动呈正弦函数
        self.speed = ra.randint(5,10)     #爱心移动速度
        self.color = ra.choice(colors)    #爱心的颜色
        self.outline = 1                  #爱心的外框大小(可不要)
    def move(self):                    #爱心移动函数
        if self.y <= 500:            #当爱心还在画布中时
            self.y += self.speed     #设置上下移动速度
            self.x += self.speed * math.sin(self.f)    #设置左右移动速度
            self.f += 0.1            #可以理解成标志,改变左右移动的方向
        else:                        #当爱心漂出了画布时,重新生成一个爱心
            self.r = ra.randint(10,15)
            self.x = ra.randint(-1000,1000)
            self.y = -500
            self.f = ra.uniform(-3.14,3.14)
            self.speed = ra.randint(5,10)
            self.color = ra.choice(colors)
            self.outline = 1
    def draw(self):       #画爱心函数,就是用turtle画爱心
        t.pensize(self.outline)
        t.penup()
        t.color(self.color)
        t.goto(self.x, self.y)
        t.pendown()
        t.begin_fill()
        t.fillcolor('pink')
        t.setheading(120)
        t.circle(self.r, 195)
        t.fd(self.r * 2.4)
        t.lt(90)
        t.fd(self.r * 2.4)
        t.circle(self.r, 195)
        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. Dynamic effects in canvas.

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

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

By cyclically calling the move() and draw() operations on each Heart object, the entire screen will dynamically form a floating effect of many hearts. Through the differentiation of attributes 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 functions 

def Love():
    root=tk.Tk()
    width=200
    height=50
    screenwidth=root.winfo_screenwidth()
    screenheight=root.winfo_screenheight()
    x=ra.randint(0,screenwidth)
    y=ra.randint(0,screenheight)
    root.title("❤")
    root.geometry("%dx%d+%d+%d"%(width,height,x,y))
    tk.Label(root,text='I LOVE YOU!',fg='white',bg='pink',font=("Comic Sans MS",15),width=30,height=5).pack()
    root.mainloop()
def Heart():
    root=tk.Tk()
    screenwidth=root.winfo_screenwidth()
    screenheight=root.winfo_screenheight()
    width=600
    height=400
    x=(screenwidth-width)//2
    y=(screenheight-height)//2
    root.title("❤")
    root.geometry("%dx%d+%d+%d"%(screenwidth,screenheight,0,0))
    tk.Label(root,text='❤',fg='pink',bg='white',font=("Comic Sans MS",500),width=300,height=20).pack()
    root.mainloop()

Two functions Love() and Heart() are defined in this program to achieve a romantic effect that expresses love.

The Love() function implements a pop-up window, the window title is "❤", and the main body of the window 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.

Guess you like

Origin blog.csdn.net/m0_59595915/article/details/132495123