Python 2.7 Tkinter on close function - python-2.7

im making a small app which opens a box using Tkinter when a certain condition is reached.
I dont want to spam the user with theses boxes so i want tkinter to set a variable to True when it starts up, then as it closes set it back to False.
Im making a down website checker/notifier so once the website is back up you get a pop up box letting you know. Right now if you close the box the code will continue and the box will pop up again. However the real problem is the code wont continue in the background.
If i make the code continue to run in the background the every 5 seconds of the conditions being met, another box will pop up and eventually spam the user which is something i dont want.
is there a way to check if there is a tkinter box open, or set a value to false when the close button (or X button) is pressed ?

You can redefine what the close button does:
win = Toplevel()
win.protocol('WM_DELETE_WINDOW', close(win))
def close(window):
window.withdraw()
someboolean = False
Hope this helps!

You can register a callback function for the WM_DELETE_WINDOW (the window is about to be deleted)
Example1:
top = Toplevel()
def on_close(t):
flag = False
t.protocol("WM_DELETE_WINDOW", on_close)
You can also override the destroy function:
Example2:
class CustomToplevel(Toplevel):
def destroy(self):
# Add you code here
Toplevel.destroy(self)

Related

How to unfocus the user dialog while it is being displayed in matlab?

If, e.g, a script contains button or a list it seems that the user is unable to edit other objects (e.g like figures) while the button or list box is actively being displayed on the screen. Therefore I would like to ask if I can "unfocus" the button so that I can freely edit the desired object (e.g zoom in/out, add manuallly a legend etc.)?
E.g:
while indx == 1
list = {[...
'Choose_option',...
'The data file will be exported (with a total of_____'...
num2str(height(EXPORT))'_____datapoints)'],...
};
[indx] = listdlg('SelectionMode','single','ListString',list,'ListSize', [600 300]);
switch indx
case 1
% placeholder
case 2
source_1 ='D:\MyFile\Programm_alpha\Test.xls';
destination_1 ='D:\TargetEXPO\Programm_beta'
copyfile(source_1 , destination_1);
xlswrite(source_1,{'Begin_reading'},'Sheet_1','A1');
end
end
listdlg creates a modal dialog box, which means it disables interaction with everything else in MATLAB until the dialog box is closed. The same is true for inputdlg and questdlg.
If you want to have a non-modal window where the user can select things, you will have to build this yourself. You will need uicontrol for this. A good place to start is by looking at the code for listdlg (it used to be a plain M-file back in the day, not sure if it still is though).

Is it possible to stop Tkinter window freezing during update?

I have a small python project that requires data to be pulled from a network and displayed every second (which is how often it changes) for a scientific application. 3 of these things are simply numbers, while another is a 128x128 camera image, which is brought in as an ndarray and drawn using matplotlib's imshow to a tkinter canvas.
I've tried two methods - using aniamtion.FuncAnimation() and after(interval, function), and both have the same result, which is that while the frame updates, the window can't be moved. and it feels jerky.
I assume that's something that can't be overcome (and probably doesn't matter)? I thought that perhaps multi-threading might help so the main window is on one thread, while the updated data can be on another?
Thanks!
Below is the basic code which now includes threading, and the error when closing the window is fixed by adding an event to the window close function, and also a few break commands while getting data that checks if the window is closed before it tries to interact with a GUI item that doesn't exist.
import blah, blah, blah
global safe_shutdown, window_status, my_thread
safe_shutdown = False
window_status = True
window = tk.Tk()
def widow_close():
window_status=False
while True:
if safe_shutdown == True:
window.destroy
return False
def get_updates():
while True:
#code to go get data from network
if window_status == False:
safe_shutdown == True:
break
#more code to place data on the GUI
if window_status == False:
safe_shutdown == True:
break
#only get updates once a second
time.sleep(1)
print "thread complete"
my_thread= threading.Thread(target=get_updates, args=()).start()
window.protocol("WM_DELETE_WINDOW", window_close)
window.mainloop()
I'm not an expert, so I'm not sure if there's a better solution. But I've had success with two separate solutions:
1: While it is not recomended to have the tkinter loop in a thread, you are allowed to have the data updating the tkinter app in a thread. This has worked pretty good for me in the past simply using the threading package. The thread will then just set the various stuff in need of a refresh.
2: Call the update_idletasks() on the window to force it to update. This can then be added at various places in you code where it would make sense to update the view.
Solution 1 whould take care of all stuttering, while solution 2 might just make it a bit better. I suppose it depends on your implementation.

Setting a breakpoint in pycharm changes the behavior of the code

That's really a Pycharm - IDE question - the python/wx bug is fixed.
A seemingly innocuous change broke the raceText.SetLabel() call (which simply sets the text in the static text control) below. So I set a breakpoint in item = self.items[itemDex]:
def __init__(self):
# ...
self.raceText = staticText(self,u'') # see below for staticText definition
def EvtListBox(self,event):
"""Responds to listbox selection."""
itemDex = event.GetSelection()
item = self.items[itemDex] # breakpoint here
face = self.data[item]
self.nameText.SetLabel(face.pcName)
self.raceText.SetLabel(face.getRaceName()) # this
Lo and behold self.raceText.SetLabel(face.getRaceName()) now succeeded.
So how is this possible ? What does setting a breakpoint trigger ?
EDIT: some more data:
What originally broke the SetLabel() call was this commit:
-def staticText(parent,label=u'',pos=defPos,size=defSize,style=0,name=u"staticText",id=defId,):
+def staticText(parent, label=u'', pos=defPos, size=defSize, style=0,
+ noAutoResize=True, name=u"staticText"):
"""Static text element."""
- return wx.StaticText(parent,id,label,pos,size,style,name)
+ if noAutoResize: style |= wx.ST_NO_AUTORESIZE
+ return wx.StaticText(parent, defId, label, pos, size, style, name)
Flipping noAutoResize default value to False squashed the bug - the text was set but wx.ST_NO_AUTORESIZE would prevent the control to adjust its size from u'' - so no text was displayed. So this was a plain old bug.
The question remains why on earth when setting a breakpoint in the debugger self.raceText.SetLabel() shows the text ?
EDIT: do read the answer - sanity check
IIUC, I think it's possible that running in the debugger is simply hiding or confusing the real issue.
When wx.ST_NO_AUTORESIZE is not set then changes to the label will cause the widget's size to be adjusted, which will typically cause the widget to be repainted soon via an automatic paint event from the system. When wx.ST_NO_AUTORESIZE is set, then the resize doesn't happen and so that particular paint event doesn't happen and the widget may not get repainted until the next time the parent is refreshed or something else happens that triggers a paint event.
So a likely fix would be to add a call to self.fooText.Refresh() after each SetLabel. The display will still not be updated while stopped in the debugger because the paint event normally won't happen until return to the active event loop, but in a normal run it will happen soon enough that the user will not notice unless there is some long-running thing blocking the return to the event loop.

can't get values from variable in tkinter

app=Tk()
age=IntVar()
name=StringVar()
id=IntVar()
def add_user():
app1=Tk()
L1 = Message(app1,text="Name")
L1.pack( side = LEFT)
E1 = Entry(app1,textvariable=name)
E1.pack()
L2 = Message(app1,text="\nAge")
L2.pack( side = LEFT)
E2 = Spinbox(app1,from_=1,to_=100,textvariable=age)
E2.pack()
l3=Message(app1,text="\nId")
l3.pack()
e3=Spinbox(app1,from_=1,to_=100,textvariable=id)
e3.pack()
b5=Button(app1,text="submit",command=app1.destroy)
b5.pack()
app1.mainloop()
print age.get(),name.get(),id.get()
return
b1=Button(app,command=add_user,relief=RIDGE,text="add patient details")
b1.pack(side=BOTTOM)
app.mainloop()
the print statement doesn't print the correct values,it always prints the default values.I don't understand where I made a mistake
The reason you can't get the values is that the widgets have been destroyed once mainloop has exited.
The bigger problem in your code is that you are creating two instances of Tk. Tkinter isn't designed to work that way. A proper Tkinter program creates exactly one instance of Tk, and exits when that one instance is destroyed. If you want to create more than one window, the second and subsequent windows need to be instances of Toplevel.
You might find the answer to this question useful: Correct way to implement a custom popup tkinter dialog box

Text does not display when Show() is used, but does when ShowModal() is used. (wxPython)

I am analyzing an image and it takes a little while to process. I want to have a Dialog box pop up when a user clicks the 'Analyze' button. I need it to be modeless so it does not interrupt the flow of my application (so the analyzing actually occurs). I just want it to display "Analyzing image..." until the analysis is done, at which point it goes away (meaning I don't want any buttons). Here is what I have so far:
class MessageDialog(wx.Dialog):
def __init__(self, message, title):
wx.Dialog.__init__(self, None, -1, title,size=(300, 120))
self.CenterOnScreen(wx.BOTH)
text = wx.StaticText(self, -1, message)
box = wx.BoxSizer(wx.VERTICAL)
box.Add(text, 1, wx.ALIGN_CENTER, 10)
self.SetSizer(box)
I call it from my main application frame using:
msg_dialog = MessageDialog("Analyzing image...", "Analyzing")
msg_dialog.Show()
# Do some stuff.....
msg_dialog.Destroy()
When I use msg_dialog.Show() the "Analyzing image..." text does not show up. If I change it to msg_dialog.ShowModal(), the text shows up. I can't use ShowModal() though because it pauses my program, defeating the purpose of the box. Any ideas about what's going on? Thanks for the help.
You need to call wxWindow::Update() to force the update of the controls on the screen without returning to the event loop.
You could also just use wxBusyInfo.