[Worker's Fishing Series] Python is a Pikachu table pet, and the work is efficient.

Hello everyone! I am a red panda ❤

Yesterday, a little friend in the penguin skirt said that he wanted me to use Python for the wholedesktop widget~

It's not fun enough to be a calendar~

Today, let's meet the needs of our little friends~

Simply bring everyone to a wholedesktop petRight ~
(By the way, I'm using an excuse to fish hahahahahaha)


If you have any python-related error answers that you can't answer, or source code/module installation/women's clothing masters are proficient in skills, you can come here: ( https://jq.qq.com/?_wv=1027&k=2Q3YTfym ) or +V: python10010 ask me


Please add image description

Do you like Pikachu~ Let's be a Pikachu today as an example! !

Related documents

Disclaimer: The picture material comes from the Internet, please apologize for deletion.

development tools

  • Python version: 3.6.4

Related modules:

  • PyQt5 module;

And some modules that come with Python.

Environment setup and installation

Python and add it to the environment variable, and pip installs the required related modules.

Please add image description


Introduction

Since I want to write a desktop pet, the first thing is to find the picture material of the pet~

Here we use pet image materials from the shimiji mobile app, such as Pikachu:

Please add image description

I have downloaded about 60 kinds of pet image materials for you to choose from:

Please add image description

They are all packaged and provided in related files, so the crawler code will not be shared here (I picked it up, as long as I don't think it's particularly ugly, I basically keep it), don't put unnecessary stress on the home server.

Next, we can start designing our desktop pet.

In view of the fact that the desktop pendants written in python on the Internet are basically based on tkinter, in order to highlight the difference of the official account, here we use PyQt5 to implement our desktop pet.

First, let's initialize a desktop pet's window component:

class DesktopPet(QWidget):
    def __init__(self, parent=None, **kwargs):
        super(DesktopPet, self).__init__(parent)
        self.show()

Its effect is like this:
Please add image description
Next, we set the properties of the window to make it more suitable as a pet window:

# 初始化
self.setWindowFlags(Qt.FramelessWindowHint|Qt.WindowStaysOnTopHint|Qt.SubWindow)
self.setAutoFillBackground(False)
self.setAttribute(Qt.WA_TranslucentBackground, True)
self.repaint()

And randomly import a pet image to see the running effect:

# 随机导入一个宠物
self.pet_images, iconpath = self.randomLoadPetImages()
# 当前显示的图片
self.image = QLabel(self)
self.setImage(self.pet_images[0][0]

The function code for randomly importing all pictures of a pet is implemented as follows:

'''随机导入一个桌面宠物的所有图片'''
def randomLoadPetImages(self):
    pet_name = random.choice(list(cfg.PET_ACTIONS_MAP.keys()))
    actions = cfg.PET_ACTIONS_MAP[pet_name]
    pet_images = []
    for action in actions:
        pet_images.append([self.loadImage(os.path.join(cfg.ROOT_DIR, pet_name, 'shime'+item+'.png')) for item in action])
    iconpath = os.path.join(cfg.ROOT_DIR, pet_name, 'shime1.png')
    return pet_images, iconpath

Please add image description

Of course, we also hope that the pet's position on the desktop is random every time, which will be more interesting:

'''随机到一个屏幕上的某个位置'''
def randomPosition(self):
    screen_geo = QDesktopWidget().screenGeometry()
    pet_geo = self.geometry()
    width = (screen_geo.width() - pet_geo.width()) * random.random()
    height = (screen_geo.height() - pet_geo.height()) * random.random()
    self.move(width, height)

Now, when we run our program, the effect is like this:
Please add image description
it seems pretty good~

Wait, there seems to be a problem, after resetting the window properties,

How do you get out of this shit? It seems strange to add a symbol like an × in the upper right corner of the pet?

Don't worry, we can add a tray icon to our desktop pet to realize the exit function of the desktop pet program:

# 设置退出选项
quit_action = QAction('退出', self, triggered=self.quit)
quit_action.setIcon(QIcon(iconpath))
self.tray_icon_menu = QMenu(self)
self.tray_icon_menu.addAction(quit_action)
self.tray_icon = QSystemTrayIcon(self)
self.tray_icon.setIcon(QIcon(iconpath))
self.tray_icon.setContextMenu(self.tray_icon_menu)
self.tray_icon.show()

The effect is like this:
Please add image description
OK, it seems to be like this~

But it still doesn't seem right.

The position of this pet is randomly generated on the desktop each time,

But we can't adjust the position of this pet, which is obviously unreasonable,

As a desktop pet, you must not be in a position that interferes with the owner's work!

Please add image description

Why don't we write the functions when the mouse is pressed, moved and released,

This makes it possible to drag it with the mouse:

'''鼠标左键按下时, 宠物将和鼠标位置绑定'''
def mousePressEvent(self, event):
    if event.button() == Qt.LeftButton:
        self.is_follow_mouse = True
        self.mouse_drag_pos = event.globalPos() - self.pos()
        event.accept()
        self.setCursor(QCursor(Qt.OpenHandCursor))
'''鼠标移动, 则宠物也移动'''
def mouseMoveEvent(self, event):
    if Qt.LeftButton and self.is_follow_mouse:
        self.move(event.globalPos() - self.mouse_drag_pos)
        event.accept()
'''鼠标释放时, 取消绑定'''
def mouseReleaseEvent(self, event):
    self.is_follow_mouse = False
    self.setCursor(QCursor(Qt.ArrowCursor))

The effect is as follows:

Please add image description
Haha, it's getting more and more decent~

Finally, as a lively pet, you can't be so rigid and motionless, can you?

Anyway, you have to learn to make expressions to make your master happy, right?

OK, let's set up a timer first:

# 每隔一段时间做个动作
self.timer = QTimer()
self.timer.timeout.connect(self.randomAct)
self.timer.start(500)

The timer switches the picture of the selected pet at regular intervals.

In order to achieve the animation effect of pets doing facial expressions (the basic content of the video is composed of frame-by-frame pictures, I don't need to come to science T_T).

Of course, here we have to classify pictures by action (pictures doing the same action belong to the same category),

Ensure the continuity of pet expressions.

Specifically, the code is implemented as follows:

'''随机做一个动作'''
def randomAct(self):
    if not self.is_running_action:
        self.is_running_action = True
        self.action_images = random.choice(self.pet_images)
        self.action_max_len = len(self.action_images)
        self.action_pointer = 0
    self.runFrame()
'''完成动作的每一帧'''
def runFrame(self):
    if self.action_pointer == self.action_max_len:
        self.is_running_action = False
        self.action_pointer = 0
        self.action_max_len = 0
    self.setImage(self.action_images[self.action_pointer])
    self.action_pointer += 1
'''随机做一个动作'''
def randomAct(self):
    if not self.is_running_action:
        self.is_running_action = True
        self.action_images = random.choice(self.pet_images)
        self.action_max_len = len(self.action_images)
        self.action_pointer = 0
    self.runFrame()
'''完成动作的每一帧'''
def runFrame(self):
    if self.action_pointer == self.action_max_len:
        self.is_running_action = False
        self.action_pointer = 0
        self.action_max_len = 0
    self.setImage(self.action_images[self.action_pointer])
    self.action_pointer += 1

OK, you're done

For the complete source code, please refer to the relevant documents. For
the final effect, see the effect display section~

Show results

Run the following command in the cmd window:

python DesktopPet.py

The effect is as follows:
Please add image description
Please add image description
I don't know why it was originally a dynamic picture, but I can't show it, I can only take a screenshot for everyone to see! ! (Sometimes I'm speechless)

That's it for today's article~

I'm Red Panda, see you in the next article (✿◡‿◡)

Please add image description

Supongo que te gusta

Origin blog.csdn.net/m0_67575344/article/details/126623800
Recomendado
Clasificación