Post

tkinter를 공부해보자!

파이썬으로 shimejiee 같은 나를 힐링시켜줄 프로그램을 만들어보고 싶다는 생각에 시작한 기록

고양이 코드

아직 이것저것 시도해 보고 있기도 하고 문제가 많은 코드이기에 나중에 천천히 수정 할 것

내 컴퓨터 고양이.zip

mycomputerpet

version 1

고양이 코드
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
import pyautogui
import random
import tkinter as tk
import pystray
from pystray import Menu
from pystray import MenuItem as item
from PIL import Image
from win32api import GetMonitorInfo, MonitorFromPoint
import os

#변수설정
check = 1 #행동변수
cycle = 0 #frame 체크
x = 0
y = 0
click_cocunt = 0
event_number = random.randrange(1, 3, 1)
idle_num =[1,2,3,4]
sleep_num = [10,11,12,13,15]
walk_left = [6,7]
walk_right = [8,9]
grab_num = [16]

#윈도우 설정
window = tk.Tk()
impath = '.\\motions\\' #motions\idle.gif
window.wm_attributes("-topmost", 1)
win_width = window.winfo_screenwidth()
win_height = window.winfo_screenheight()
app_width = 100
app_height = 100

center_width = (win_width / 2) - (app_width / 2 )
center_height = (win_height / 2 ) - (app_height / 2)

monitor_info = GetMonitorInfo(MonitorFromPoint((0,0)))
monitor_area = monitor_info.get("Monitor")
work_area = monitor_info.get("Work")
task_area = monitor_area[3] - work_area[3]
print("The taskbat height is {}.".format(task_area))#tack bar 위치

print("모니터 사이즈 : ",win_width, win_height)
print("모니터 중심점 : ", int(center_height), int(center_width))
window.resizable(False, False)
window.geometry(f"{app_width}x{app_height}+{int(center_width)}+{int(win_height - task_area - app_height)}")# 윈도우 크기100x100 이고 위치 모니터 정 중앙 이 아니라 taskbar 위




#투명화
window.config(highlightbackground='black')
label = tk.Label(window,bd=0,bg='black')
window.overrideredirect(True)
window.wm_attributes('-transparentcolor','black')
canbas= tk.Canvas(window, width=win_width, height=win_height, bg = 'black')
label.pack()


#아이콘 트레이 행동

def action_test():
    print("HI")

def quit_window(icon, item):
    icon.visible = False
    icon.stop()
    window.configure(bg='white')
    window.quit()#확인
    print("종료합니다.")

def size_character():
   app_width#아직 하는중

def show_window(icon, item):
    window.after(0, window.deiconify)

def size_up(icon, item):
   print('size up')

def size_down(icon, item):
   print('size down')

def new_window():
   global new
   new = window.Toplevel()#오류

def Add_character(icon, item):
   print('add character')
   new_window()

def Reduce_character(icon, item):
   print('reduce_character')

def reset_position(icon, item):
   x = 0
   window.after(100, x)

def set_position_left():
   x =- 100
   window.after(100, x)

def set_position_right(x):
   x =- 100
   print("right")
   return x

def withdraw_window():
    window.withdraw()

def remove_character():
    window.iconify()

def position_by_mouse():
   x, y = window.winfo_pointerx(), window.winfo_pointery()
   return x, y

def click_detect():
    window.bind("<Button-1>", count)

def count(event):
    if event.num == 1:
        window.after(1, update, cycle, check,  x, y, 1)



#gif 파일 불러오기
idle = [tk.PhotoImage(file=impath+'idle.gif',format = 'gif -index %i' %(i)) for i in range(5)]#idle gif
idle_to_sleep = [tk.PhotoImage(file=impath+'idle_to_sleep.gif',format = 'gif -index %i' %(i)) for i in range(8)]#idle to sleep gif
sleep = [tk.PhotoImage(file=impath+'sleep.gif',format = 'gif -index %i' %(i)) for i in range(3)]#sleep gif
sleep_to_idle = [tk.PhotoImage(file=impath+'sleep_to_idle.gif',format = 'gif -index %i' %(i)) for i in range(8)]#sleep to idle gif
walk_positive = [tk.PhotoImage(file=impath+'walking_positive_remake.gif',format = 'gif -index %i' %(i)) for i in range(8)]#walk to left gif
walk_negative = [tk.PhotoImage(file=impath+'walking_negative_remake.gif',format = 'gif -index %i' %(i)) for i in range(8)]#walk to right gif
grab_by_mouse = [tk.PhotoImage(file=impath+'grab_by_mouse.gif', format = 'gif -index %i' %(i)) for i in range(2)] #grabed by mouse


#이미지 불러오기 테스트

def gif_work(cycle,frames,event_number,first_num,last_num):
 if cycle < len(frames) -1:
  cycle+=1
 else:
  cycle = 0
  event_number = random.randrange(first_num,last_num+1,1)
 return cycle,event_number


def event(cycle,check,event_number,x,y,click_count):
    if event_number in grab_num:
        check = 6
        window.after(50, update,cycle, check, event_number,x, y) #mouse grab action = 16
    if event_number in idle_num:
        check = 0
        #print('idle')
        window.after(400,update,cycle,check,event_number,x, y) #no. 1,2,3,4 = idle
    elif event_number == 5:
        check = 1
        #print('from idle to sleep')
        window.after(100,update,cycle,check,event_number,x, y) #no. 5 = idle to sleep
    elif event_number in walk_left:
        check = 4
        #print('walking towards left')
        window.after(100,update,cycle,check,event_number,x, y)#no. 6,7 = walk towards left
    elif event_number in walk_right:
        check = 5
        #print('walking towards right')
        window.after(100,update,cycle,check,event_number,x, y)#no 8,9 = walk towards right
    elif event_number in sleep_num:
        check  = 2
        #print('sleep')
        window.after(1000,update,cycle,check,event_number,x, y)#no. 10,11,12,13,15 = sleep
    elif event_number == 14:
        check = 3
        #print('from sleep to idle')
        window.after(100,update,cycle,check,event_number,x, y)#no. 15 = sleep to idle


def update(cycle,check,event_number,x,y,click_count):
 if click_cocunt == 1:
    check = 6
 #idle
 if check ==0:
  frame = idle[cycle]
  cycle ,event_number = gif_work(cycle,idle,event_number,1,9)  
 #idle to sleep
 elif check ==1:
  frame = idle_to_sleep[cycle]
  cycle ,event_number = gif_work(cycle,idle_to_sleep,event_number,10,10)
#sleep
 elif check == 2:
  frame = sleep[cycle]
  cycle ,event_number = gif_work(cycle,sleep,event_number,10,15)
#sleep to idle
 elif check ==3:
  frame = sleep_to_idle[cycle]
  cycle ,event_number = gif_work(cycle,sleep_to_idle,event_number,1,1)
#walk toward left
 elif check == 4:
  frame = walk_positive[cycle]
  cycle , event_number = gif_work(cycle,walk_positive,event_number,1,9)
  x -= 3
#walk towards right
 elif check == 5:
  frame = walk_negative[cycle]
  cycle , event_number = gif_work(cycle,walk_negative,event_number,1,9)
  x -= -3
 
 elif check == 6:
    frame = grab_by_mouse[cycle]
    cycle , event_number = gif_work(cycle, grab_by_mouse, event_number, 1, 9) #이거 이미지 프레임 단위
    x, y = position_by_mouse()


 window.geometry(f"{app_width}x{app_height}+{int(center_width)+int(x)}+{int(win_height - task_area - app_height)+int(y)}")# 윈도우 크기100x100 이고 위치 모니터 정 중앙 이 아니라 taskbar 위
 label.configure(image=frame)
 window.after(1,event,cycle,check,event_number,x,y,click_cocunt)

#아이콘 트레이 몸체
image_path = Image.open(impath + 'icon-modified.png')
menu = ( 
         item('TEST', action_test),
         item('Quit', quit_window), 
         item('size', Menu(item('size up', size_up), item('size down', size_down))),
         item('Cat Num', Menu(item('Add', Add_character), item('Reduce', Reduce_character))),
         #item('set position_test', Menu(item('reset', reset_position), item('left', set_position_left), item('right', set_position_right))),
        )
icon = pystray.Icon("PET", image_path, "PET_VIEW", menu)

#메인 루프
icon.run_detached()
window.after(10, update, cycle, check, event_number, x, y, click_cocunt)
window.configure(bg = 'black')
window.protocol('WM_DELETE_WINDOW', withdraw_window)
window.mainloop()
This post is licensed under CC BY 4.0 by the author.