Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
483 views
in Technique[技术] by (71.8m points)

user interface - Using pygame features in Tkinter

I'd like to use some features from pygame (sprite graphics) in my GUI I made in Tkinter. I know of OcempGUI, but I'd prefer to stick to Tkinter, just use some modules from pygame. This is similar but not quite the same. Is this possible at all? What are potential problems (event loop)?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This works on Linux. If you're lucky, it might work on other operating systems as well.

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()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...