The difference between the two examples, is that first one keeps a reference to the widget as a global variable, whilst the second creates a local variable that gets garbage-collected when it goes out of scope (i.e. when the function returns).
The simplest way to fix this, is to make the ex
variable global, like this:
def main():
global ex
ex = Example()
or you could just get rid of the main
function, and simply do:
if __name__ == '__main__':
ex = Example()