[英]Why does my tkinter messagebox not show up in my pygame window?
I coded a snake game and whenever you hit your own body, a message box should show up asking u to play again.我编写了一个贪吃蛇游戏,每当你撞到自己的身体时,都会出现一个消息框,要求你再玩一次。 However, when I do hit the body, my python pygame window just closes without showing the message box.
然而,当我击中身体时,我的 python pygame window 只是关闭而不显示消息框。 I coded all this in Idle, could it be because I'm using idle?
我在 Idle 中编写了所有这些代码,可能是因为我正在使用 idle 吗? Or is there a problem with my code?
还是我的代码有问题?
Here are my code:这是我的代码:
import math
import random
import pygame
import tkinter as tk
from tkinter import messagebox
class cube (object) :
rows = 20
w = 500
def __init__(self,start,dirnx=1,dirny=0,color=(255,0,0)):
self.pos = start
self.dirnx = 1
self.dirny = 0
self.color = color
def move(self, dirnx, dirny) :
self.dirnx = dirnx
self.dirny = dirny
self.pos = (self.pos[0]+ self.dirnx, self.pos[1] + self.dirny)
def draw(self, surface, eyes=False) :
dis = self.w // self.rows
i = self.pos[0]
j = self.pos[1]
pygame.draw.rect(surface, self.color, (i*dis+1,j*dis+1, dis-2, dis-2))
if eyes:
centre = dis//2
radius = 3
circleMiddle = (i*dis+centre-radius,j*dis+8)
circleMiddle2 = (i*dis + dis -radius*2, j*dis+8)
pygame.draw.circle(surface, (0,0,0), circleMiddle, radius)
pygame.draw.circle(surface, (0,0,0), circleMiddle2, radius)
class snake(object) :
body = []
turns = {}
def __init__(self, color, pos) :
self.color = color
self.head = cube(pos)
self.body.append(self.head)
self.dirnx = 0
self.dirny = 1
def move(self) :
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
keys = pygame.key.get_pressed()
for key in keys:
if keys[pygame.K_LEFT]:
self.dirnx = -1
self.dirny = 0
self.turns[self.head.pos[:]] = [self.dirnx, self.dirny]
elif keys[pygame.K_RIGHT]:
self.dirnx = 1
self.dirny = 0
self.turns[self.head.pos[:]] = [self.dirnx, self.dirny]
elif keys[pygame.K_UP]:
self.dirnx = 0
self.dirny = -1
self.turns[self.head.pos[:]] = [self.dirnx, self.dirny]
elif keys[pygame.K_DOWN]:
self.dirnx = 0
self.dirny = 1
self.turns[self.head.pos[:]] = [self.dirnx, self.dirny]
for i, c in enumerate(self.body) :
p = c.pos[:]
if p in self.turns:
turn = self.turns[p]
c.move(turn[0], turn[1])
if i == len(self.body)-1:
self.turns.pop(p)
else:
if c.dirnx == -1 and c.pos[0] <= 0: c.pos = (c.rows-1, c.pos[1])
elif c.dirnx == 1 and c.pos[0] >= c.rows-1: c.pos = (0,c.pos[1])
elif c.dirny == 1 and c.pos[1] >= c.rows-1: c.pos = (c.pos[0], 0)
elif c.dirny == -1 and c.pos[1] <= 0: c.pos = (c.pos[0],c.rows-1)
else: c.move(c.dirnx,c.dirny)
def reset(self, pos) :
self.head = cube(pos)
self.body = []
self.body.append(self.head)
self.turns = {}
self.dirnx = 0
self.dirny = 1
def addCube(self) :
tail = self.body[-1]
dx, dy = tail.dirnx, tail.dirny
if dx == 1 and dy == 0: #if an elif statements checking which direction the tail is moving
self.body.append(cube((tail.pos[0]-1,tail.pos[1])))
#appending a cube to the tail. checking if we r moving in a certain direction and then adding the snack cube to the pos 1 less than tail cube
elif dx == -1 and dy == 0:
self.body.append(cube((tail.pos[0]+1,tail.pos[1])))
elif dx == 0 and dy == 1:
self.body.append(cube((tail.pos[0],tail.pos[1]-1)))
elif dx == 0 and dy == -1:
self.body.append(cube((tail.pos[0],tail.pos[1]+1)))
self.body[-1].dirnx = dx
self.body[-1].dirny = dy
def draw(self, surface) :
for i, c in enumerate(self.body):
if i == 0:
c.draw(surface, True)
else:
c.draw(surface)
def drawGrid(w, rows, surface) :
sizeBtwn = w // rows
x = 0
y = 0
for l in range(rows) :
x = x + sizeBtwn
y = y + sizeBtwn
pygame.draw.line(surface,(255,255,255), (x,0), (x,w))
pygame.draw.line(surface,(255,255,255), (0,y), (w,y))
def redrawWindow(surface) :
global rows, width, s, snack
surface.fill((0,0,0))
s.draw(surface)
snack.draw(surface)
drawGrid(width,rows, surface)
pygame.display.update()
def randomSnack(rows, item) :
positions = item.body
while True:
x = random.randrange(rows)
y = random.randrange(rows)
if len(list(filter(lambda z:z.pos == (x,y), positions))) > 0:
#lambda z is a fucntion. we r checking if this z.pos is equal to x,y. if its equal to x,y we will have to continue it again
continue
else:
break
return (x,y)
def message_box(subject, content) :
root = tk.Tk()
root.attributes("-topmost", True)
root.withdraw()
messagebox.showinfo(subject, content)
try:
root.destroy()
except:
pass
def main() :
global width, rows, s, snack
width = 500
rows = 20
win = pygame.display.set_mode((width, width))
s = snake((255,0,0), (10,10))
snack = cube(randomSnack(rows, s), color=(0,255,0))
flag = True
clock = pygame.time.Clock()
while flag:
pygame.time.delay(50)
clock.tick(10)
s.move()
if s.body[0].pos == snack.pos:
s.addCube()
snack = cube(randomSnack(rows, s), color=(0,255,0))
for x in range (len(s.body)):
if s.body[x].pos in list(map(lambda z:z.pos,s.body[x+1:])):
print("Score:", len(s.body))
message_box("Loser!", "Get stressed again?")
s.reset((10,10))
break
#looping through every cube in snake body, checking if the pos is in a list of all the positions after
redrawWindow(win)
pass
main()
Any help is appreciated, thank you!感谢您的帮助,谢谢!
Update: I moved my code to VS code and the same thing happens.更新:我将我的代码移动到 VS 代码,同样的事情发生了。 This is what shows up in the terminal after python unexpected closes:
这是 python 意外关闭后终端中显示的内容:
2022-03-12 12:28:55.740 Python[26287:549611] -[SDLApplication macOSVersion]: unrecognized selector sent to instance 0x141f35cc0
2022-03-12 12:28:55.749 Python[26287:549611] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[SDLApplication macOSVersion]: unrecognized selector sent to instance 0x141f35cc0'
*** First throw call stack:
(
0 CoreFoundation 0x00000001873ac1cc __exceptionPreprocess + 240
1 libobjc.A.dylib 0x00000001870fd7b8 objc_exception_throw + 60
2 CoreFoundation 0x000000018743f1a0 -[NSObject(NSObject) __retain_OA] + 0
3 CoreFoundation 0x000000018730c360 ___forwarding___ + 1728
4 CoreFoundation 0x000000018730bbe0 _CF_forwarding_prep_0 + 96
5 libtk8.6.dylib 0x00000001067acb1c GetRGBA + 64
6 libtk8.6.dylib 0x00000001067ac5a8 SetCGColorComponents + 140
7 libtk8.6.dylib 0x00000001067ac9e0 TkpGetColor + 544
8 libtk8.6.dylib 0x000000010670e554 Tk_GetColor + 220
9 libtk8.6.dylib 0x0000000106701ba0 Tk_Get3DBorder + 204
10 libtk8.6.dylib 0x00000001067019ac Tk_Alloc3DBorderFromObj + 144
11 libtk8.6.dylib 0x000000010670f910 DoObjConfig + 832
12 libtk8.6.dylib 0x000000010670f4cc Tk_InitOptions + 348
13 libtk8.6.dylib 0x000000010670f3c8 Tk_InitOptions + 88
14 libtk8.6.dylib 0x0000000106736df0 CreateFrame + 1448
15 libtk8.6.dylib 0x00000001067370e8 TkListCreateFrame + 156
16 libtk8.6.dylib 0x000000010672ffc0 Initialize + 1848
17 _tkinter.cpython-310-darwin.so 0x00000001062322d4 Tcl_AppInit + 92
18 _tkinter.cpython-310-darwin.so 0x0000000106231f6c Tkapp_New + 548
19 _tkinter.cpython-310-darwin.so 0x0000000106231d44 _tkinter_create_impl + 268
20 _tkinter.cpython-310-darwin.so 0x000000010623197c _tkinter_create + 240
21 Python 0x0000000105c2afa4 cfunction_vectorcall_FASTCALL + 88
22 Python 0x0000000105cfa160 call_function + 132
23 Python 0x0000000105cf2190 _PyEval_EvalFrameDefault + 24188
24 Python 0x0000000105ceaae4 _PyEval_Vector + 360
25 Python 0x0000000105bc42dc _PyObject_FastCallDictTstate + 96
26 Python 0x0000000105c57a3c slot_tp_init + 196
27 Python 0x0000000105c4e6d0 type_call + 312
28 Python 0x0000000105bc4024 _PyObject_MakeTpCall + 136
29 Python 0x0000000105cfa258 call_function + 380
30 Python 0x0000000105cf2190 _PyEval_EvalFrameDefault + 24188
31 Python 0x0000000105ceaae4 _PyEval_Vector + 360
32 Python 0x0000000105cfa160 call_function + 132
33 Python 0x0000000105cf042c _PyEval_EvalFrameDefault + 16664
34 Python 0x0000000105ceaae4 _PyEval_Vector + 360
35 Python 0x0000000105cfa160 call_function + 132
36 Python 0x0000000105cf042c _PyEval_EvalFrameDefault + 16664
37 Python 0x0000000105ceaae4 _PyEval_Vector + 360
38 Python 0x0000000105d55534 pyrun_file + 308
39 Python 0x0000000105d54c78 _PyRun_SimpleFileObject + 336
40 Python 0x0000000105d542c4 _PyRun_AnyFileObject + 216
41 Python 0x0000000105d803c4 pymain_run_file_obj + 180
42 Python 0x0000000105d7fa64 pymain_run_file + 72
43 Python 0x0000000105d7f04c pymain_run_python + 300
44 Python 0x0000000105d7eee0 Py_RunMain + 24
45 Python 0x0000000105d8056c pymain_main + 56
46 Python 0x0000000105d80830 Py_BytesMain + 40
47 dyld 0x000000010514d0f4 start + 520
)
libc++abi: terminating with uncaught exception of type NSException
zsh: abort /usr/local/bin/python3
Does it mean anything?这意味着什么吗?
You made a typo.你打错了。 When you called
messagebox
to display the messagebox, you accidentally put an underscore.当你调用
messagebox
来显示 messagebox 时,你不小心放了一个下划线。 Instead of代替
message_box("Loser!", "Get stressed again?")
Do:做:
messagebox("Loser!", "Get stressed again?")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.