473,795 Members | 2,498 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How to terminate a TkinterApp correctly?

I'm working on a windows machine

I've written a Tkinter-app (sort of game) which
consists mainly of an animation which is driven
by a while True: ... loop.

If I close the App's window by clicking the
right upper standard-X-Button, the program
doesn't terminate cleanly. Instead a somewhat
cryptic error message is displayed, e.g.:

.....
TclError: invalid command name ".12880040.1288 0944"

which - I suppose - stems from the interpreter trying
to execute some statement in the infinite loop.

Only if this loop is terminated by some other means
- e.g. game over - before closing the window no
error message is displayed.

How, i.e. by what sort of event handler or error handler
can I avoid this annoying behaviour of my program?

Regards, Gregor

Jul 18 '05 #1
8 5123

"Gregor Lingl" <gl****@aon.a t> schrieb im Newsbeitrag
news:3F******** ******@aon.at.. .
I'm working on a windows machine

I've written a Tkinter-app (sort of game) which
consists mainly of an animation which is driven
by a while True: ... loop.
[....] Only if this loop is terminated by some other means
- e.g. game over - before closing the window no
error message is displayed.

Correct
How, i.e. by what sort of event handler or error handler
can I avoid this annoying behaviour of my program?

You can bind <Destroy> and act accordimngly, or intercept the action
altogether.

Example:
-----------------------------
from Tkinter import *

def killingAction(e v):
print "Destroyed"

def kidding():
print "not killing"
l.config(text=" just kidding")
l.master.protoc ol("WM_DELETE_W INDOW",original )

l=Label(text="K ill me!")
l.pack()
l.bind("<Destro y>",killingActi on)

original= l.master.protoc ol("WM_DELETE_W INDOW",None)
l.master.protoc ol("WM_DELETE_W INDOW",kidding)
l.master.destro y=lambda: 0

mainloop()
--------------------------------------------

Kindly
Michael P

Regards, Gregor

Jul 18 '05 #2
I just notice a left over line from a test, that lambda is of no use at all!
May be you will have to use WM_SAVE_YOURSEL F instead of WM_DELETE_WINDO WS if
you want to be sure to keep the widget absolutly intact. Between these two
messages some tidying-up could aleady have happened behind the scene....So
this is my fine example:

-----------------------------
from Tkinter import *

def killingAction(e v):
print "Destroyed"

def kidding():
print "not killing"
l.config(text=" just kidding")
l.master.protoc ol("WM_DELETE_W INDOW",original )

l=Label(text="K ill me!")
l.pack()
l.bind("<Destro y>",killingActi on)

original= l.master.protoc ol("WM_DELETE_W INDOW",None)
l.master.protoc ol("WM_DELETE_W INDOW",kidding)
mainloop()
-------------------------------------------

Kindly
Michael P

Jul 18 '05 #3

----- Original Message -----
From: "Gregor Lingl" <gl****@aon.a t>
Newsgroups: comp.lang.pytho n
Sent: Saturday, August 16, 2003 3:53 PM
Subject: Re: How to terminate a TkinterApp correctly?

.....
Thanks for your remarks and your example. The
following solution finally did it:

def exit():
global done
done = True # so the animation will terminate, but
# not immediately! The actual pass through
# the loop has to be finished.
print "done!"
import sys
# after_idle seems to be crucial! Waits for terminating
# the loop (which is in a callback function)
cv.after_idle(s ys.exit, (0,))

Why don't you just return? The mainloop can handle everything!?
Example:
def exit(self):
self.done=1
return

(If you can put it into an appropriate class ....)

cv.master.proto col("WM_DELETE_ WINDOW", exit)

if not usingIDLE:
root.mainloop()

Regards, Gregor

Jul 18 '05 #4

"Michael Peuser" <mp*****@web.de > wrote in message
news:bh******** *****@news.t-online.com...

----- Original Message -----
From: "Gregor Lingl" <gl****@aon.a t>
Newsgroups: comp.lang.pytho n
Sent: Saturday, August 16, 2003 3:53 PM
Subject: Re: How to terminate a TkinterApp correctly?

....
Thanks for your remarks and your example. The
following solution finally did it:

def exit():
global done
done = True # so the animation will terminate, but
# not immediately! The actual pass through
# the loop has to be finished.
print "done!"
import sys
# after_idle seems to be crucial! Waits for terminating
# the loop (which is in a callback function)
cv.after_idle(s ys.exit, (0,))

Why don't you just return? The mainloop can handle everything!?


Unfortunately, the combination of Windows 9x (including Me)
and Python 2.1 can't handle everything. It may also be broken
in 2.2 and later, but I quit trying after reaching my frustration
limit. If you exit with an exception, something doesn't clean up
properly, and you break the DOS box and eventually Windows
itself when you try to shut down.

This problem doesn't exist in the Windows 2K (including XP)
code base, or other variants.

I don't know that it's ever been solved, but considering that
Windows 9x is gradually going away, it's also not a real hot
priority.

John Roth

Jul 18 '05 #5

"John Roth" <ne********@jhr othjr.com> schrieb im Newsbeitrag
news:vj******** ****@news.super news.com...

"Michael Peuser" <mp*****@web.de > wrote in message
news:bh******** *****@news.t-online.com...

----- Original Message -----
From: "Gregor Lingl" <gl****@aon.a t>
Newsgroups: comp.lang.pytho n
Sent: Saturday, August 16, 2003 3:53 PM
Subject: Re: How to terminate a TkinterApp correctly?

....
Thanks for your remarks and your example. The
following solution finally did it:

def exit():
global done
done = True # so the animation will terminate, but
# not immediately! The actual pass through
# the loop has to be finished.
print "done!"
import sys
# after_idle seems to be crucial! Waits for terminating
# the loop (which is in a callback function)
cv.after_idle(s ys.exit, (0,))

Why don't you just return? The mainloop can handle everything!?


Unfortunately, the combination of Windows 9x (including Me)
and Python 2.1 can't handle everything. It may also be broken
in 2.2 and later, but I quit trying after reaching my frustration
limit. If you exit with an exception, something doesn't clean up
properly, and you break the DOS box and eventually Windows
itself when you try to shut down.

This problem doesn't exist in the Windows 2K (including XP)
code base, or other variants.

I don't know that it's ever been solved, but considering that
Windows 9x is gradually going away, it's also not a real hot
priority.

This was not my point I think.... I was not referring to tk/system mainloop
but to your own loop you mentioned. This is where you set "done=1" for...
The after_idle is confusing and probably not what you want. I have the
impression that there is still some misunderstandin g.

It is absolutly fine to intercept the user click to the close box - there is
no magic it and - as to my example - you can do what you want for hours
after. Note: the "closing" process is stopped, when you use this WM-....
trick. (Because I was not *quite* sure about the internal states, I also
recommende to use WM_SAVE_YOURSEL F instead).

But I think it is not worth all the work - and still unsafe! - to just call
sys.exit() !!!

Kindly Michasel P

John Roth

Jul 18 '05 #6
Michael Peuser schrieb:
----- Original Message -----
From: "Gregor Lingl" <gl****@aon.a t>
Newsgroups: comp.lang.pytho n
Sent: Saturday, August 16, 2003 3:53 PM
Subject: Re: How to terminate a TkinterApp correctly?

....

Thanks for your remarks and your example. The
following solution finally did it:

def exit():
global done
done = True # so the animation will terminate, but
# not immediately! The actual pass through
# the loop has to be finished.
print "done!"
import sys
# after_idle seems to be crucial! Waits for terminating
# the loop (which is in a callback function)
cv.after_idle(s ys.exit, (0,))
Why don't you just return? The mainloop can handle everything!?
Example:
def exit(self):
self.done=1
return

Here I apparently don't understand something fundamental:
what is the effect of a return statement as the last statement
of a function?
Moreover: If I put this into the cv.master.proto col ... I cannot
close the application at all. (Because the original is not restored.
And I don't want to need a second mouseclick as in your first example.)
Gregor (If you can put it into an appropriate class ....)

cv.master.pro tocol("WM_DELET E_WINDOW", exit)

if not usingIDLE:
root.mainloop()

Regards, Gregor



Jul 18 '05 #7
Michael Peuser schrieb:
"John Roth" <ne********@jhr othjr.com> schrieb im Newsbeitrag ....
Why don't you just return? The mainloop can handle everything!?


Unfortunately ,
....I don't know that it's ever been solved, but considering that
Windows 9x is gradually going away, it's also not a real hot
priority.


This was not my point I think.... I was not referring to tk/system mainloop
but to your own loop you mentioned.


The above answer was not mine, so there is samething a bit mangled ...

This is where you set "done=1" for... The after_idle is confusing and probably not what you want.
But it worked!

I have the impression that there is still some misunderstandin g.
Maybe!
It is absolutly fine to intercept the user click to the close box - there is
no magic it and - as to my example - you can do what you want for hours
after. Note: the "closing" process is stopped, when you use this WM-....
trick. (Because I was not *quite* sure about the internal states, I also
recommende to use WM_SAVE_YOURSEL F instead).

But I think it is not worth all the work - and still unsafe! -
WHY?

to just call sys.exit() !!!
So I found another working solution to my problem:
I put the code for the go-function, which is the command of a goButton
in a try:- except: clause.

def go():
global done
try:
resetGame()
goButton["state"] = Tk.DISABLED
while fehler < MAXFEHLER and not done:
for huhn in huehner:
huhn.move()
cv.update()
done = True
goButton["state"] = Tk.NORMAL
except:
pass

This catches the TclError and everything terminates regularly
Regards, Gregor
Kindly Michasel P
John Roth



Jul 18 '05 #8

"Gregor Lingl" <gl****@aon.a t> schrieb im Newsbeitrag
news:3F******** ******@aon.at.. .
Michael Peuser schrieb:
.....
Why don't you just return? The mainloop can handle everything!?
Example:
def exit(self):
self.done=1
return

Here I apparently don't understand something fundamental:
what is the effect of a return statement as the last statement
of a function?


Nothing, just an indicator to make clear that this is the end of the
procedure...
Moreover: If I put this into the cv.master.proto col ... I cannot
close the application at all. (Because the original is not restored.
And I don't want to need a second mouseclick as in your first example.)

This is a misunderstandin g. Closing your application has nothing to do with
closing some window and even less with where a stupid user clicks on ;-)

You can destroy a widget with "destroy"; when the root widget is destroyed
then the Tkinter mainloop terminats by convention. Nothing to do with your
program!!
See this example:
---------------------------
from Tkinter import *

def killingAction() :
l.master.destro y()

def kidding():
l.config(text=" just kidding")
l=Button(text=" Kill me!",command=ki llingAction)
l.pack()

l.master.protoc ol("WM_DELETE_W INDOW",kidding)
mainloop()
print "here we are- ready for whatever we want"
-----------------------

Jul 18 '05 #9

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

Similar topics

3
11549
by: abovetreeline | last post by:
Hi, How to make javascript terminate a win32_process? vbscript will terminate a named process with the following code: strcomputer = "." Set objwmiservice = GetObject("winmgmts:" _ & "{impersonationlevel=impersonate}!\\"&strcomputer & "\root\cimv2") Set colprocesslist = objwmiservice.execquery _ ("SELECT * FROM Win32_Process WHERE Name = 'winword.exe'")
9
13064
by: liangbowen | last post by:
As i konw, the only way to to terminate a thread started by _beginthread() is to user _endthread() (or return) inside the thread. now i started a thread(TodoThread), and created a listenning socket inside the thread. I want to destroy the socket and kill the thread at anytime if there is no client connect to it. How?
4
4941
by: Dr. J | last post by:
How to terminate a blocked thread? In my form's "load" I launch a TCP listening thread that stays in an infinite loop waiting for incoming TCP packets. In this form's "closing" I try to terminate this thread by calling the "Abort" funcion. But the thread does not terminate and after the form is closed this thread keeps running at blocked state. Basically the application keeps running because this thread does not terminate while...
3
2472
by: Kathy Burke | last post by:
Hi, I'm tired, so this question may be silly. I have a fairly long sub procedure. Based on one condition, I load another sub with the following: If Session("GRN") = "complete" Then txtScan.Text = Session("SN") txtScan_TextChanged(sender, e) Session("GRN") = "" Exit Sub End If
3
13786
by: Keith Grefski | last post by:
I cant seem to figure out how to terminate a process in vb.net i can do it using vbscript and wmi but terminate doesnt seem to exist in the available classes for wmi under vb.net
3
5924
by: Peter Neuburger via .NET 247 | last post by:
(Type your message here) -------------------------------- From: Peter Neuburger Hi Everybody, I need some help with the WMI Terminate Method. I have a Listbox where I get all the Process Information using the WMI Win32_process
7
8777
by: fyi85 | last post by:
I have 8.1.5 on Windows 2003, when I do from CLP with auto commit off: db2 update table set column=something and then db2 terminate and then db2 connect to db db2 select updated column from table the update is committed anyways, whereas the docs state that the update is supposed to be rolled back (auto commit is off) Does this indicate a bug or a mistake in the docs?
0
1245
by: Scheu | last post by:
Hi all, I'm hoping someone can help me with this bizarre problem. If I create a new PerformanceCounter object in a ComVisible class and invoke it from wscript, it never seems to terminate. When debugging, Visual Studio never leaves the (running) state when the Go function exits (even clicking the 'Stop Debugging' button fails). When not debugging, the cscript / wscript.exe process never leaves memory. I've tried this same code in a...
1
7268
by: Justin | last post by:
We had a load that failed. Now we have a pending load. When executing load terminate, we receive the following error: db2 load terminate SQL0104N An unexpected token "terminate" was found following "LOAD". Expected tokens may include: "QUERY". SQLSTATE=42601 db2 query load terminate DB21034E The command was processed as an SQL statement because it was
0
9519
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10436
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. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9040
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
7538
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
6780
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 into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5436
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...
1
4113
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
3722
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2920
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.