PPTTER

Loading...

PPTTER

用chatGPT做一个可以准确设置窗口大小的小应用

1年前 565 阅读量

用chatGPT做一个可以准确设置窗口大小的小应用


大家拍视频需要录屏的时候,不知道会不会遇到和我一样的问题,就是总要手动把窗口的分辨率设置为1920×1080像素,不然就怕后期的时候不够清晰,但是每次手动设置又很烦,所以今天我们就用chatGPT4配合python来完成一个小应用,可以方便快捷的把应用尺寸设置成我们希望的大小。

1、首先告诉chatGPT:我们来做一个py小程序,小程序内有一个列表,列表内有可以看到当前正在运行的程序列表,这个时候GPT就给到了我们第一版的代码:

import psutil

def get_running_processes():
    process_list = []
    for process in psutil.process_iter(['pid', 'name']):
        process_list.append(f"{process.info['pid']} - {process.info['name']}")
    return process_list

def main():
    print("当前正在运行的程序列表:")
    running_processes = get_running_processes()
    for process_info in running_processes:
        print(process_info)

if __name__ == "__main__":
    main()
代码运行结果如下:

发现代码直接在命令行输出结果了,这明显不符合我们的要求,继续给GPT喂指令

2、接下来告诉chatGPT,我们需要一个GUI的交互界面,而不是在命令行里输出结果,于是我们有了第二版代码:

import psutil
import tkinter as tk

def get_running_processes():
    process_list = []
    for process in psutil.process_iter(['pid', 'name']):
        process_list.append(f"{process.info['pid']} - {process.info['name']}")
    return process_list

def main():
    root = tk.Tk()
    root.title("当前正在运行的程序列表")

    canvas = tk.Canvas(root, width=600, height=400)
    canvas.pack()

    running_processes = get_running_processes()
    y_offset = 20
    for process_info in running_processes:
        canvas.create_text(10, y_offset, anchor=tk.W, text=process_info)
        y_offset += 20

    root.mainloop()

if __name__ == "__main__":
    main()
代码运行结果如下:

现在我们已经有一个软件窗体了,接下来我们再继续和chatGPT合作,让这些现实出来的进程可以点击,为下一步的工作做铺垫

3、接下来我们告诉chatGPT,我们需要这些现实出来的进程可以点击,类似VB的list控件效果,然后我们就得到了第三版的代码:

import psutil
import tkinter as tk

def get_running_processes():
    process_list = []
    for process in psutil.process_iter(['pid', 'name']):
        process_list.append(f"{process.info['pid']} - {process.info['name']}")
    return process_list

def on_process_selected(event):
    selected_process = listbox.get(listbox.curselection())
    print(f"选中的进程: {selected_process}")

def main():
    root = tk.Tk()
    root.title("当前正在运行的程序列表")

    listbox = tk.Listbox(root, width=50, height=20)
    listbox.pack(padx=10, pady=10)

    running_processes = get_running_processes()
    for process_info in running_processes:
        listbox.insert(tk.END, process_info)

    listbox.bind(">", on_process_selected)

    root.mainloop()

if __name__ == "__main__":
    main()
代码运行结构如下:

现在,我们可以用鼠标点击进程了,而且还能在控制台看到被点击的进程输出了对应的名称

4、现在我们要进行一点小优化,因为现在把所有的进程里显示出来了,有些进程是系统进程根本就没有必要显示,而且也改不了大小,因为它根本就没有窗口,所以我们告诉chatGPT加一个筛选功能,把在任务栏中显示的,可以调整窗口大小的进程筛选出来,以下是chatGPT根据我们的要求给出的代码:

import psutil
import tkinter as tk

def get_running_processes():
    process_list = []
    for process in psutil.process_iter(['pid', 'name']):
        process_list.append(f"{process.info['pid']} - {process.info['name']}")
    return process_list

def main():
    root = tk.Tk()
    root.title("当前正在运行的程序列表")

    listbox = tk.Listbox(root, width=50, height=20)
    listbox.pack(padx=10, pady=10)

    running_processes = get_running_processes()
    for process_info in running_processes:
        listbox.insert(tk.END, process_info)

    def on_process_selected(event):
        selected_process = listbox.get(listbox.curselection())
        print(f"选中的进程: {selected_process}")

    listbox.bind(">", on_process_selected)

    root.mainloop()

if __name__ == "__main__":
    main()
运行结果如下:

现在刚我们勾选“仅显示可见窗口程序”的时候,列表里就只显示正在任务栏运行的代码了

5、接下来,我们添加两个input控件和一个button控件,这样我们就可以输入自定义的尺寸了,chatGPT给出的代码如下:

import psutil
import tkinter as tk
import ctypes
from ctypes import windll, POINTER, byref, WinError
from ctypes.wintypes import BOOL, HWND, LPARAM, MAX_PATH

def is_window_visible(hwnd):
    return windll.user32.IsWindowVisible(hwnd) != 0

def get_running_processes(only_visible_windows=False):
    process_list = []

    def window_enum_callback(hwnd, lparam):
        length = windll.user32.GetWindowTextLengthW(hwnd)
        if length > 0 and is_window_visible(hwnd):
            process_id = ctypes.wintypes.DWORD()
            windll.user32.GetWindowThreadProcessId(hwnd, ctypes.byref(process_id))
            process = psutil.Process(process_id.value)
            process_info = f"{process.pid} - {process.name()}"
            if process_info not in process_list:
                process_list.append(process_info)
        return True

    if only_visible_windows:
        EnumWindowsProc = ctypes.WINFUNCTYPE(BOOL, HWND, LPARAM)
        windll.user32.EnumWindows(EnumWindowsProc(window_enum_callback), 0)
    else:
        for process in psutil.process_iter(['pid', 'name']):
            process_list.append(f"{process.info['pid']} - {process.info['name']}")

    return process_list

def main():
    root = tk.Tk()
    root.title("当前正在运行的程序列表")

    show_visible_windows_var = tk.BooleanVar()

    def update_listbox(only_visible_windows=False):
        listbox.delete(0, tk.END)
        running_processes = get_running_processes(only_visible_windows)
        for process_info in running_processes:
            listbox.insert(tk.END, process_info)

    def on_checkbox_toggle():
        update_listbox(show_visible_windows_var.get())

    def on_process_selected(event):
        selected_process = listbox.get(listbox.curselection())
        print(f"选中的进程: {selected_process}")

    show_visible_windows_checkbox = tk.Checkbutton(root, text="仅显示可见窗口程序", variable=show_visible_windows_var, command=on_checkbox_toggle)
    show_visible_windows_checkbox.pack(pady=(0, 10))

    width_label = tk.Label(root, text="宽度:")
    width_label.pack()
    width_entry = tk.Entry(root)
    width_entry.pack()

    height_label = tk.Label(root, text="高度:")
    height_label.pack()
    height_entry = tk.Entry(root)
    height_entry.pack()

    def on_confirm_click():
        width = width_entry.get()
        height = height_entry.get()
        print(f"设置的宽度: {width}, 高度: {height}")

    confirm_button = tk.Button(root, text="确定", command=on_confirm_click)
    confirm_button.pack(pady=(10, 10))

    listbox = tk.Listbox(root, width=50, height=20)
    listbox.pack(padx=10, pady=10)

    update_listbox()

    listbox.bind(">", on_process_selected)

    root.mainloop()

if __name__ == "__main__":
    main()
运营结果如下图:

6、现在最后一步,让chatGPT根据我们输入的尺寸,把选中的应用程序窗口尺寸跟改成我们制定的大小,代码如下:

import psutil
import tkinter as tk
import tkinter.messagebox
import ctypes
from ctypes import windll, POINTER, byref, WinError
from ctypes.wintypes import BOOL, HWND, LPARAM, MAX_PATH

selected_hwnd = None

# print hello word in python

def is_window_visible(hwnd):
    return windll.user32.IsWindowVisible(hwnd) != 0

def get_running_processes(only_visible_windows=False):
    process_list = []

    def window_enum_callback(hwnd, lparam):
        length = windll.user32.GetWindowTextLengthW(hwnd)
        if length > 0 and is_window_visible(hwnd):
            process_id = ctypes.wintypes.DWORD()
            windll.user32.GetWindowThreadProcessId(hwnd, ctypes.byref(process_id))
            process = psutil.Process(process_id.value)
            process_info = (hwnd, f"{process.pid} - {process.name()}")
            if process_info not in process_list:
                process_list.append(process_info)
        return True

    if only_visible_windows:
        EnumWindowsProc = ctypes.WINFUNCTYPE(BOOL, HWND, LPARAM)
        windll.user32.EnumWindows(EnumWindowsProc(window_enum_callback), 0)
    else:
        for process in psutil.process_iter(['pid', 'name']):
            process_list.append((None, f"{process.info['pid']} - {process.info['name']}"))

    return process_list

def main():
    root = tk.Tk()
    root.title("当前正在运行的程序列表")

    show_visible_windows_var = tk.BooleanVar()

    def update_listbox(only_visible_windows=False):
        listbox.delete(0, tk.END)
        running_processes = get_running_processes(only_visible_windows)
        for process_info in running_processes:
            listbox.insert(tk.END, process_info[1])

    def on_checkbox_toggle():
        global selected_hwnd
        selected_hwnd = None
        update_listbox(show_visible_windows_var.get())

    def on_process_selected(event):
        global selected_hwnd
        if listbox.curselection():
            selected_process = listbox.get(listbox.curselection())
            print(f"选中的进程: {selected_process}")
            selected_hwnd = next((item[0] for item in get_running_processes(only_visible_windows=True) if item[1] == selected_process), None)
        else:
            selected_hwnd = None

    show_visible_windows_checkbox = tk.Checkbutton(root, text="仅显示可见窗口程序", variable=show_visible_windows_var, command=on_checkbox_toggle)
    show_visible_windows_checkbox.pack(pady=(0, 10))

    width_label = tk.Label(root, text="宽度:")
    width_label.pack()
    width_entry = tk.Entry(root)
    width_entry.insert(0, "1920")
    width_entry.pack()

    height_label = tk.Label(root, text="高度:")
    height_label.pack()
    height_entry = tk.Entry(root)
    height_entry.insert(0, "1080")
    height_entry.pack()

    def on_confirm_click():
        if not selected_hwnd:
            tk.messagebox.showerror("错误", "请先选择一个可视化窗口的进程")
            return

        width = int(width_entry.get())
        height = int(height_entry.get())

        SWP_NOZORDER = 0x0004
        SWP_NOACTIVATE = 0x0010
        windll.user32.SetWindowPos(selected_hwnd, None, 0, 0, width, height, SWP_NOZORDER | SWP_NOACTIVATE)

    confirm_button = tk.Button(root, text="确定", command=on_confirm_click)
    confirm_button.pack(pady=(10, 10))

    listbox = tk.Listbox(root, width=50, height=20)
    listbox.pack(padx=10, pady=10)

    update_listbox()

    listbox.bind(">", on_process_selected)

    root.mainloop()

if __name__ == "__main__":
    main()
代码效果如下:

现在,我们就可以在选中chrome(或任何程序)后自由快速设定窗口的尺寸了

P友的态度

不喜欢

不喜欢 不喜欢

SamanSaul

wongvio

赞赏

赞赏 赞赏

wongvio

喜欢

喜欢 喜欢

wongvio

SamanSaul

高兴

高兴 高兴

wongvio

2 个用户表态

565 阅读量

P一下! 表个态!

like
love
dislike
wow
funny
happy
sad
angry

评论

赞助

加载更多 1+

1

更多推荐

最新发布

【Midjourney】星光璀璨的奇妙之夜

9个月前

【Midjourney】星光璀璨的奇妙之夜

在这个奇妙的夜晚,我们被带入了一个梦幻般的仙境。这个场景如此精细、如此锐利,就像是超高清摄影的杰作。一位美丽的少女正在一颗巨大的树上攀爬,她的全身尽收......

详情...

129 阅读量

【Midjourney】巴哈马之晨

9个月前

【Midjourney】巴哈马之晨

清晨的阳光洒在巴哈马的大地上,给一座木屋镶上了金边。站在木屋门廊上的是一位高大、崭露锐气的巴哈马汉子,他身着一件蓝色衬衫,黑皮肤透露着健康的光泽。这位......

详情...

135 阅读量