2011-03-14 73 views
0

有誰知道如何將pygame與Tk集成?我正嘗試用Tk形式驅動pygame顯示器,並且遇到困難。下面是我試圖完成的一種簡單的例子。我試圖從Tk表單輸入觸發pygame窗口中的動作。我不知道如何克服基本的互動。任何人做這種類型的事情?建議?Python集成pygame和tk

# 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(): 
+0

你似乎錯過的'身體高清的main():' – Ikke

回答

0

你看過嗎PyToolkit?它看起來像你正在尋找的橋樑。嗯,只是,不,下載鏈接都死了:-(

1

我已經試過這一點。其主要思想是設置使用root.after(miliseconds, call_back)一個計時器事件。這將在你的Tk的程序tirgger 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的窗口會作何反應,你