2026년 5월 24일 일요일

Tkinter 대시보드 실행 안 될 때, 진짜 문제 3가지와 바로 되는 수정 코드

핵심부터 말씀드립니다.
이 코드는 구조 자체는 맞습니다.
실행이 안 되는 이유는 대부분 3가지 중 하나입니다.


✔ 질문자 현재 상황

  • 윈도우10 / 64비트 / 파이썬 사용
  • Tkinter + psutil + GPUtil + ctypes 사용
  • 서브모니터용 대시보드 만들려고 함
  • “실행이 안 됨” → 오류 메시지 없이 멈추거나 실행 안 되는 상태

✔ 가장 흔한 원인 3가지

원인 설명 해결
GPUtil 오류 GPU 없거나 드라이버 문제 예외 처리 필요
ctypes EnumWindows 문제 콜백 함수 타입 오류 함수 구조 수정
쓰레드 충돌 Tkinter + threading 불안정 UI 업데이트 분리 유지

✔ 사람들이 많이 헷갈리는 부분

  • Tkinter는 메인 쓰레드에서만 UI 조작 가능
  • ctypes 콜백은 타입 안 맞으면 조용히 실패
  • GPUtil은 환경 따라 바로 터짐

✔ 수정된 정상 동작 코드

import tkinter as tk
import psutil
import threading
import time
import ctypes

try:
    import GPUtil
except:
    GPUtil = None

user32 = ctypes.windll.user32

class FullScreenDashboard:
    def __init__(self, root):
        self.root = root
        self.root.title("Sub-Monitor Dashboard")

        self.root.geometry("1920x1080-1920+0")
        self.root.overrideredirect(True)
        self.root.configure(bg="#0a0a0c")

        self.data = {"cpu": "0%", "ram": "0%", "gpu": "N/A", "media": "음악을 재생해주세요."}

        self.lbl_media = tk.Label(root, text=self.data["media"],
                                  font=("Arial", 50, "bold"),
                                  fg="white", bg="#0a0a0c", wraplength=1700)
        self.lbl_media.place(x=100, y=300)

        self.lbl_stats = tk.Label(root, text="데이터 수집 중...",
                                  font=("Arial", 30),
                                  fg="#00bbf9", bg="#0a0a0c")
        self.lbl_stats.place(x=100, y=700)

        threading.Thread(target=self.update_data, daemon=True).start()
        self.update_ui()

    def get_media_title(self):
        titles = []

        @ctypes.WINFUNCTYPE(ctypes.c_bool, ctypes.c_int, ctypes.c_int)
        def enum_handler(hwnd, lParam):
            if user32.IsWindowVisible(hwnd):
                length = user32.GetWindowTextLengthW(hwnd)
                if length > 0:
                    buf = ctypes.create_unicode_buffer(length + 1)
                    user32.GetWindowTextW(hwnd, buf, length + 1)
                    title = buf.value
                    if any(x in title for x in ["Melon", "Spotify", "YouTube", "멜론"]):
                        titles.append(title)
            return True

        user32.EnumWindows(enum_handler, 0)
        return titles[0] if titles else "음악을 재생해주세요."

    def update_data(self):
        while True:
            try:
                self.data["cpu"] = f"{psutil.cpu_percent()}%"
                self.data["ram"] = f"{psutil.virtual_memory().percent}%"

                if GPUtil:
                    gpus = GPUtil.getGPUs()
                    self.data["gpu"] = f"{int(gpus[0].load * 100)}%" if gpus else "N/A"

                self.data["media"] = self.get_media_title()

            except Exception as e:
                print(e)

            time.sleep(1)

    def update_ui(self):
        self.lbl_media.config(text=self.data["media"])
        self.lbl_stats.config(
            text=f"CPU: {self.data['cpu']} | GPU: {self.data['gpu']} | RAM: {self.data['ram']}"
        )
        self.root.after(1000, self.update_ui)


root = tk.Tk()
app = FullScreenDashboard(root)
root.mainloop()

✔ 현실적인 체크 리스트

  • pip install psutil GPUtil 했는지 확인
  • GPU 없는 PC면 GPUtil 제거해도 됨
  • 서브모니터 좌표 맞는지 확인
  • 콘솔에서 에러 출력되는지 반드시 확인


✔ 한줄 정리

이 코드는 구조 문제가 아니라 ctypes 콜백 + GPUtil + 환경 문제로 실행이 막히는 경우입니다.



0개의 덧글:

댓글 쓰기

에 가입 댓글 [Atom]

<< 홈