Python 集成 pygame 和 tk
有没有人知道怎么把pygame和Tk结合起来?我想用一个Tk的表单来控制pygame的显示,但遇到了一些困难。下面是我想实现的一个简单例子。我想从Tk的表单获取输入,然后在pygame窗口中触发一些动作。我不太确定怎么才能做到基本的互动。有没有人做过这种事情?有什么建议吗?
# The following code has 2 major problems.
# 1. The window does not refresh when it is dragged over the pygame field.
# 2. How to plot variables on the screen when the 'Draw' button is clicked?
from Tkinter import *
import os, sys, pygame
from pygame.locals import *
pygame.init()
size = width, height = 1200, 800
CENTER = width/2, height/2
class Application(Frame):
def draw_circle(self):
print "How do I draw a circle at (x,y) radius?"
print "Does this code belong here?"
def createWidgets(self):
myXFrame = Frame(self, bd=2, relief=RIDGE)
Label(myXFrame, text='X:').pack(side=LEFT, padx=5)
myX = StringVar()
Entry(myXFrame, textvariable=myX, bg='white').pack(side=RIGHT, padx=5)
myX.set('X')
myXFrame.pack(expand=1, fill=X, pady=10, padx=5)
myYFrame = Frame(self, bd=2, relief=RIDGE)
Label(myYFrame, text='Y:').pack(side=LEFT, padx=5)
myY = StringVar()
Entry(myYFrame, textvariable=myY, bg='white').pack(side=RIGHT, padx=5)
myY.set('Y')
myYFrame.pack(expand=1, fill=X, pady=10, padx=5)
radiusFrame = Frame(self, bd=2, relief=RIDGE)
Label(radiusFrame, text='Radius:').pack(side=LEFT, padx=5)
radius = StringVar()
Entry(radiusFrame, textvariable=radius, bg='white').pack(side=RIGHT, padx=5)
radius.set('radius')
radiusFrame.pack(expand=1, fill=X, pady=10, padx=5)
self.DRAW = Button(self)
self.DRAW["text"] = "DRAW"
self.DRAW["fg"] = "red"
self.DRAW["command"] = self.draw_circle
self.DRAW.pack({"side": "left"})
def __init__(self, master=None):
Frame.__init__(self, master)
self.pack()
self.createWidgets()
def main():
相关问题:
2 个回答
0
你有没有看过 PyToolkit?这个东西看起来正是你需要的桥梁。不过,唉,下载链接好像都坏掉了 :-(
1
我试过这个方法。主要的思路是使用 root.after(毫秒数, 回调函数) 来设置一个定时事件。这样可以在你的 Tk 程序中触发 pygame 的部分。
下面是一个例子。
import pygame
import Tkinter as tk
from random import randint
class MyGame:
def __init__(self):
self.root = tk.Tk()
tk.Button(self.root, text='Click Me', command=self.add_point).pack()
pygame.display.init()
self.screen = pygame.display.set_mode((200, 200))
self.screen.fill(0xffffff)
pygame.display.flip()
self.cnt = 0
def add_point(self, r=20):
pygame.draw.circle(self.screen, randint(0, 0xffffff),
(randint(10, 190), randint(10, 190)), r)
pygame.display.flip()
def loop(self):
# do logic
# do render
self.cnt += 1
if self.cnt % 10 == 0:
self.add_point(3)
self.root.after(5, self.loop)
def mainloop(self):
self.root.after(5, self.loop)
self.root.mainloop()
MyGame().mainloop()
点击按钮,pygame 窗口就会做出反应。