473,703 Members | 3,067 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Mixing Txinter and Pygame

Hi everyone, I'm glad to have found this list.

I've written a small script for my own use which, amongst other things,
captures mouse click information from a window containing an image. I
used Pygame to manage the image window, as it was the easiest way to
implement the functionality I needed. The surrounding interface windows
(there are two) are constructed with Tkinter.

Despite their unholy union, Pygame and Tkinter seem, generally, to
cooperate. I'm using this main loop to update one, then the other:

while 1:
gameLoop() # This function pumps the Pygame events and checks for
mouse and keyboard events
pygame.time.wai t(10)
mainwin.update( ) # mainwin is an instance of Application class,
which is a child of Tkinter.frame

I have my interface set up so that when *any* of the windows' close
boxes are clicked, this function will be called:

# This portion of the Pygame loop calls doquit() when it gets a 'QUIT'
event...
def gameLoop():
pygame.event.pu mp()
for event in pygame.event.ge t():
if event.type == QUIT:
doquit()
# Etc.

# And this portion of the Tkinter interface sets the
WM_DELETE_WINDO W protocol to call doquit()
def createWidgets(s elf):
self.title("Reg ion Management")
self.geometry(' +830+8')
self.protocol(" WM_DELETE_WINDO W", doquit)
# Etc.

# A temporary file is removed, and both Pygame and Tkinter are
instructed to quit
def doquit():
if os.access('reca lc.tmp', os.F_OK):
os.remove('reca lc.tmp')
pygame.quit()
mainwin.master. destroy()

Perhaps you've begun to see where I might be having problems. You see,
if I close the script by closing the Pygame window, I get this exception:

Traceback (most recent call last):
File "D:\Development \Python\sludge helpers\addScre enRegion
helper.pyw", line 363, in ?
mainwin.update( )
File "C:\Python24\li b\lib-tk\Tkinter.py", line 859, in update
self.tk.call('u pdate')
TclError: can't invoke "update" command: application has been destroyed

Conversely, if I close the application by closing a Tkinter window, I
get this exception:

Traceback (most recent call last):
File "D:\Development \Python\sludge helpers\addScre enRegion
helper.pyw", line 361, in ?
gameLoop()
File "D:\Development \Python\sludge helpers\addScre enRegion
helper.pyw", line 203, in gameLoop
pygame.event.pu mp()
error: video system not initialized

Obviously, Pygame doesn't like Tkinter telling it to quit (when it's
trying to do something from its internal loop) and vice versa. Is there
a simple way that I can avoid getting these exceptions on exit, or have
I taken the wrong approach? Everything else appears to work fine. Please
do excuse me if this seems a silly question, as I'm fairly new to Python
and Pygame, and a total novice when it comes to Tkinter.

On a side note, has anyone else found the Tkinter documentation awfully
obscure? I've found Python a joy to learn about, and Pygame's tutorials
are a lot of fun. I can't say the same for Tkinter, and found myself
having to do many Google searches before I uncovered information I could
put to use. Has anyone found any high-quality (online) documentation
that proves me wrong? :^)

Thanks in advance,
Tim Knauf
Jul 18 '05 #1
3 3716
On Tue, 22 Feb 2005 13:17:37 +1300, Tim Knauf <ti*@upperorbit .com> wrote:
Hi everyone, I'm glad to have found this list.

I've written a small script for my own use which, amongst other things,
captures mouse click information from a window containing an image. I
used Pygame to manage the image window, as it was the easiest way to
implement the functionality I needed. The surrounding interface windows
(there are two) are constructed with Tkinter.

Despite their unholy union, Pygame and Tkinter seem, generally, to
cooperate. I'm using this main loop to update one, then the other:

while 1:
gameLoop() # This function pumps the Pygame events and checks for
mouse and keyboard events
pygame.time.wai t(10)
mainwin.update( ) # mainwin is an instance of Application class,
which is a child of Tkinter.frame

I have my interface set up so that when *any* of the windows' close
boxes are clicked, this function will be called:

# This portion of the Pygame loop calls doquit() when it gets a 'QUIT'
event...
def gameLoop():
pygame.event.pu mp()
for event in pygame.event.ge t():
if event.type == QUIT:
doquit()
# Etc.

# And this portion of the Tkinter interface sets the
WM_DELETE_WINDO W protocol to call doquit()
def createWidgets(s elf):
self.title("Reg ion Management")
self.geometry(' +830+8')
self.protocol(" WM_DELETE_WINDO W", doquit)
# Etc.

# A temporary file is removed, and both Pygame and Tkinter are
instructed to quit
def doquit():
if os.access('reca lc.tmp', os.F_OK):
os.remove('reca lc.tmp')
pygame.quit()
mainwin.master. destroy()

Perhaps you've begun to see where I might be having problems. You see,
if I close the script by closing the Pygame window, I get this exception:

Traceback (most recent call last):
File "D:\Development \Python\sludge helpers\addScre enRegion
helper.pyw", line 363, in ?
mainwin.update( )
File "C:\Python24\li b\lib-tk\Tkinter.py", line 859, in update
self.tk.call('u pdate')
TclError: can't invoke "update" command: application has been destroyed

Conversely, if I close the application by closing a Tkinter window, I
get this exception:

Traceback (most recent call last):
File "D:\Development \Python\sludge helpers\addScre enRegion
helper.pyw", line 361, in ?
gameLoop()
File "D:\Development \Python\sludge helpers\addScre enRegion
helper.pyw", line 203, in gameLoop
pygame.event.pu mp()
error: video system not initialized

Obviously, Pygame doesn't like Tkinter telling it to quit (when it's
trying to do something from its internal loop) and vice versa. Is there
a simple way that I can avoid getting these exceptions on exit, or have
I taken the wrong approach? Everything else appears to work fine. Please
do excuse me if this seems a silly question, as I'm fairly new to Python
and Pygame, and a total novice when it comes to Tkinter.
Well, since these are just exceptions, a simple try... except block would be fine, and you can even figure out the reason for the exception. Here is what I'd do:
- when you create your Tkinter main window, initialize an attribute that you'll use to see if the application has quit, e.g mainwin.hasQuit = False
- rewrite doquit this way:
def doquit():
if os.access('reca lc.tmp', os.F_OK):
os.remove('reca lc.tmp')
mainwin.hasQuit = True
pygame.quit()
- rewrite your custom event loop this way:
while 1:
gameLoop()
pygame.time.wai t(10)
try:
mainwin.update( )
except TclError:
if not mainwin.hasQuit :
raise

And: (1) your problem should go away; (2) the "real" exceptions you may get from Tkinter windows should not passed unnoticed.
On a side note, has anyone else found the Tkinter documentation awfully
obscure? I've found Python a joy to learn about, and Pygame's tutorials
are a lot of fun. I can't say the same for Tkinter, and found myself
having to do many Google searches before I uncovered information I could
put to use. Has anyone found any high-quality (online) documentation
that proves me wrong? :^)


Incomplete, but very useful: http://www.pythonware.com/library/tk...tion/index.htm
But the best reference documentation you'll ever find is the tcl/tk man pages, on-line here: http://www.tcl.tk/man/tcl8.4/TkCmd/contents.htm
It unfortunately requires to know how to convert the tcl/tk syntax to Python/Tkinter syntax, but it is actually quite easy (mainly read "option=val ue" when the tcl/tk documentation says "-option value")

HTH
- Eric Brunel -
Jul 18 '05 #2
Eric Brunel wrote:

Well, since these are just exceptions, a simple try... except block
would be fine, and you can even figure out the reason for the
exception. Here is what I'd do:
- when you create your Tkinter main window, initialize an attribute
that you'll use to see if the application has quit, e.g
mainwin.hasQuit = False
- rewrite doquit this way:
def doquit():
if os.access('reca lc.tmp', os.F_OK):
os.remove('reca lc.tmp')
mainwin.hasQuit = True
pygame.quit()
- rewrite your custom event loop this way:
while 1:
gameLoop()
pygame.time.wai t(10)
try:
mainwin.update( )
except TclError:
if not mainwin.hasQuit :
raise

And: (1) your problem should go away; (2) the "real" exceptions you
may get from Tkinter windows should not passed unnoticed.

I adapted your suggestion slightly, and my final event loop looks like this:

while not mainwin.hasQuit :
try:
gameLoop()
except pygame.error:
if not mainwin.hasQuit :
raise
pygame.time.wai t(10)
try:
mainwin.update( )
except Tkinter.TclErro r:
if not mainwin.hasQuit :
raise

That seems to work perfectly. Thanks, Eric!
Incomplete, but very useful:
http://www.pythonware.com/library/tk...tion/index.htm
But the best reference documentation you'll ever find is the tcl/tk
man pages, on-line here: http://www.tcl.tk/man/tcl8.4/TkCmd/contents.htm
It unfortunately requires to know how to convert the tcl/tk syntax to
Python/Tkinter syntax, but it is actually quite easy (mainly read
"option=val ue" when the tcl/tk documentation says "-option value")


Ah, yes, I had managed to find the pythonware.com pages in my travels,
and they proved quite helpful. Good to know about the man pages, too.
(When I'm starting on a language feature, though, I usually find I learn
a lot more from worked examples than from straight command information.
I have friends who are just the opposite, so I suppose it's just a
learning styles thing.)

wxPython seems to be highly regarded. I might experiment with that for
my next project, and see which framework I like the best. Thanks again.
Jul 18 '05 #3
On Wed, 23 Feb 2005 10:23:09 +1300, Tim Knauf <bu**@upperorbi t.com> wrote:
[snip]
(When I'm starting on a language feature, though, I usually find I learn
a lot more from worked examples than from straight command information.


You may be interested in Tkinter best kept secret: the example scripts in the Demo/tkinter sub-directory of the Python source installation. It mainly covers the basics, but may be quite helpful when you start.

HTH
- eric -
Jul 18 '05 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

12
16126
by: Marian Aldenhövel | last post by:
Hi, I am trying to make pygame play music on windows. This simple program: import pygame,time pygame.init() print "Mixer settings", pygame.mixer.get_init() print "Mixer channels", pygame.mixer.get_num_channels() pygame.mixer.music.set_volume(1.0) pygame.mixer.music.load('file1.mp3)
2
2075
by: Brent W. Hughes | last post by:
I'm just starting to learn pygame. I write what I think is just about the simplest program that should display a window and then quit. #----------------------------------------------- import sys import time import pygame pygame.init() screen = pygame.display.set_mode((640,480)) pygame.display.set_caption("A Bug's Life")
1
3232
by: kjm | last post by:
Hi everyone, I have recently acquired a Logitech Rumble pad to use as an input device. I have been having trouble getting the event que to respond that a button or hat arrow has been pressed. This is on a system running OS 10.3.9. I have modified/written a small piece of code that initializes the joystick, and pygame does recognize it. I was wondering if someone has a small snippet of code to get me going? I have posted the code...
0
1454
by: Lunpa | last post by:
My project: I'm working on a game, where in the ui, it takes the pygame window, and shoves it into a gtk2 socket widget. (gtk2 widgets are generated with glade, with the exception of the socket widget, which is manualy added into a window) My problem: Since adding the gtk half, it is realy slow. I can make one or the other update realy fast, or I can make it so the pygame window/widget gets a fluctuation in framerate between realy...
1
6820
by: liuliuliu | last post by:
hi -- sorry if this is trivial -- but how do you make a screenshot of a pygame display? i have a surface which is basically the entire visible screen -- how do you write this surface as an image file during specific events in the script execution? image format doesnt matter. thanks! christine
11
3620
by: dynamo | last post by:
Hi guys i have come again with more problems.This time it has to do with pygame.The following code does not give any error messages but it does not do what it is supposed to do either.the code is a bit long but it's straightforward.Please help import pygame from pygame.locals import * pygame.init() screen=pygame.display.set_mode((900,900)) class Hero(pygame.sprite.Sprite): def __init__(self): ...
3
4416
by: globalrev | last post by:
im doing this : http://www.learningpython.com/2006/03/12/creating-a-game-in-python-using-pygame-part-one/ and when closing the program the window stays up and doesnt respond. i tried adding this: http://www.pygame.org/wiki/FrequentlyAskedQuestions bu it doesnt work, or maybe im doing it wrong. heres the code without the added tutorial exit:
11
11675
by: globalrev | last post by:
http://www.pygame.org/docs/ref/mixer.html import pygame #pygame.mixer.init(frequency=22050, size=-16, channels=2, buffer=3072) //it complained abiout words= so i guess its only the nbrs should be there// pygame.mixer.init(22050, -16, 2, 3072) pygame.mixer.music.load("example1.mp3")
5
3029
by: defn noob | last post by:
Im using PyGame to draw images of graphs and trees. Howver right now i am looping using: while 1: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() screen.fill(screencolor) pygame.draw.circle(screen, linecolor, (500, 20), 12, 0)
0
8759
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
1
9017
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8966
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7872
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6588
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4433
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4687
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3125
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2455
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.