【发布时间】:2016-06-03 08:52:20
【问题描述】:
我有 2 个独立的程序,都是从 Stack Overflow 获得的,并且都可以独立运行。这是第一个:
import tkinter as tk
import os
w, h = 500, 200
# Add a couple widgets. We're going to put pygame in `embed`.
root = tk.Tk()
embed = tk.Frame(root, width=w, height=h)
embed.pack()
text = tk.Button(root, text='Blah.')
text.pack()
# Tell pygame's SDL window which window ID to use
os.environ['SDL_WINDOWID'] = str(embed.winfo_id())
# The wxPython wiki says you might need the following line on Windows
# (http://wiki.wxpython.org/IntegratingPyGame).
#os.environ['SDL_VIDEODRIVER'] = 'windib'
# Show the window so it's assigned an ID.
root.update()
# Usual pygame initialization
import pygame as pg
pg.display.init()
screen = pg.display.set_mode((w,h))
pos = 0
while 1:
# Do some pygame stuff
screen.fill(pg.Color(0,0,0))
pos = (pos + 1) % screen.get_width()
pg.draw.circle(screen, pg.Color(255,255,255), (pos,100), 30)
# Update the pygame display
pg.display.flip()
# Update the Tk display
root.update()
这个程序应该在 tkinter 框架中嵌入一个 pygame 窗口,它就像一个魅力,这是第二个程序:
import pygame, random
screen = pygame.display.set_mode((800,600))
draw_on = False
last_pos = (0, 0)
color = (0, 0, 0)
white = (255,255,255)
radius = 10
screen.fill(white)
def roundline(srf, color, start, end, radius=1):
dx = end[0]-start[0]
dy = end[1]-start[1]
distance = max(abs(dx), abs(dy))
for i in range(distance):
x = int( start[0]+float(i)/distance*dx)
y = int( start[1]+float(i)/distance*dy)
pygame.draw.circle(srf, color, (x, y), radius)
try:
while True:
e = pygame.event.wait()
if e.type == pygame.QUIT:
raise StopIteration
if e.type == pygame.MOUSEBUTTONDOWN:
pygame.draw.circle(screen, color, e.pos, radius)
draw_on = True
if e.type == pygame.MOUSEBUTTONUP:
draw_on = False
if e.type == pygame.MOUSEMOTION:
if draw_on:
pygame.draw.circle(screen, color, e.pos, radius)
roundline(screen, color, e.pos, last_pos, radius)
last_pos = e.pos
pygame.display.flip()
except StopIteration:
pass
pygame.quit()
第二个应该显示一个 pygame 屏幕,你可以在上面画任何你喜欢的东西。
我不是一个非常有经验的 pygame 程序员,但是我有使用 tkinter 的经验。我想做的是制作一个你可以在上面画画的程序,但它也必须有 tkinter 按钮、条目等。
两个程序单独工作都很好,但是,当我想替换第一个程序中的 pygame 部分时,一切正常,除了我无法绘制任何东西,按钮不想被点击,我不能通过x退出,这根本没有意义,所以我在想可能有问题,反正我找不到问题,所以我很感激任何建议。
【问题讨论】:
-
只是说,你真的不应该引发异常并使用 try-catch 来打破循环
-
好的,我把它拿出来,不过我没有把它放在那里,这是我从程序中得到的,我只是下载了它:-)
标签: python user-interface python-3.x tkinter pygame