[Tutor] Why does "window = tk.Tk()" open a tkinter window when typed in the Python interpreter?

Peter Otten __peter__ at web.de
Sat Aug 29 04:13:51 EDT 2020


boB Stepp wrote:

> On Fri, Aug 28, 2020 at 5:55 PM Alan Gauld via Tutor <tutor at python.org>
> wrote:
>>
>> On 28/08/2020 22:22, Richard Damon wrote:
>>
>> >> Perhaps I should phrase the question differently:  Why does this
>> >> happen in the interpreter but does *not* happen if I run a program
>> >> without calling window.mainloop()?
>> >>
>> > Because Python when in interactive mode uses tkinter, and has a main
>> > loop of it own that will pump your messages if you don't
>> Nope, the regular Python interpreter does not use tkinter,
>> nor even need tkinter to be installed.
>>
>> This may require some examination of the source.
> 
> Are you inclined to think the source code of Tcl/Tk is where to look,
> or do you think it is how Python's wrapper, tkinter,  implements
> Tcl/Tk is where I should look?  I've been trying to research this
> online and have been unsuccessful so far -- not quite sure how to
> phrase an effective set of search terms.  I did come across that the
> scripting language, Tcl, seems to have its own interpreter mode, so
> your initial comments may be spot on if this was the behavior being
> sought up front by Tcl itself.

The following comment in Modules/_tkinter.c

/* If Tcl can wait for a Unix file descriptor, define the EventHook() 
routine
   which uses this to handle Tcl events while the user is typing commands. 
*/

indicates that the behaviour you observe is implemented in CPython.
When you run a script like

import tkinter as tk
root = tk.Tk()
button = tk.Button(root, text="Press", command=lambda: print("pressed"))
button.pack()
input()

you'll see that it's not just the look (pressing the button will work like 
expected) and that it's not limited to the interpreter.




More information about the Tutor mailing list