473,568 Members | 2,935 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 3703
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
16072
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
2073
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
3219
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....
0
1449
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...
1
6785
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
3614
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)) ...
3
4404
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...
11
11655
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
3014
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
7605
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7917
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
8118
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7665
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...
0
7962
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...
1
5501
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...
0
5217
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
1
2105
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
0
933
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.