0

I have a very simple app in Tkinkter. I am running it in Ipython Notebook.

The issue is whenever i run the app and press the button 'Get' once, nothing is returned. I press the button again and two values are returned. I press button 3 or more times and 1 value is returned per time I press the button as expected. The issue is around the first press of the button. Is there something going on I do not understand.

from tkinter import *
from tkinter import ttk, Tk 

class SampleApp(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.entry = tk.Entry(self)
        self.button = tk.Button(self, text="Get", command=self.on_button)
        self.button.pack()
        self.entry.pack()

    def on_button(self):
        value = float(self.entry.get())
        print (value*2)

app = SampleApp()
app.mainloop()

input = 5

output i get after 1 button press (not expected)

nothing

after 2 button presses (whilst i would expect 2 values at this stage, i do not expect 2 values to appear at the same time)

10

10

after 3 button presses (expected)

10

10

10

after 4 button presses (expected)

10

10

10

10

ben121
  • 879
  • 1
  • 11
  • 23
  • Correcting the indentation and namespace issues so that this actually runs, I don't see the unwanted behavior you're describing. – TigerhawkT3 Jan 04 '17 at 09:23
  • 1
    try code in normal python - not `IPython Notebook` - and see how it works. If there will be no problem then problem is `IPython Notebook` – furas Jan 04 '17 at 09:35
  • code works for me with Python 3.5 (after I changed `from tkinter import *` into `import tkinter as tk`) – furas Jan 04 '17 at 09:39

1 Answers1

0

Having searched for an answer for a while, annoyingly the answer reveals itself just after i post. Found the answer here. Whilst I am not sure i understand, the first print doesn't trigger a flush of stdout. A manual workaround is in the link or below

import sys

def on_button(self):
    value = float(self.entry.get())
    print (value*2)
    sys.stdout.flush() #place this after the print statement
Community
  • 1
  • 1
ben121
  • 879
  • 1
  • 11
  • 23
  • I still don't see the delay you describe. Have you determined why it does this on your setup? (Also, you can add `flush=True` to the `print` call to flush the output without needing to mess with `sys`.) – TigerhawkT3 Jan 04 '17 at 09:47
  • That is far cleaner and better thanks. It appears to be because the code is still running. – ben121 Jan 04 '17 at 09:50