python - Modifying a variable in a function has no result -


i have tkinter application, have mainloop typical of tkinter, , various functions handle mouse clicks , garbage.

in 1 of functions, generate string , want store string somewhere in program, can use later on if other function called or maybe if want print main loop.

import , that, here , there etc etc #blah blah global declarations   fruit = '' def somefunction(event):     blahblahblah;       fruit = 'apples'     return fruit mainwin = tk()   #blah blah blah tkinter junk #my code here #its super long don't want upload #all of works, no errors or problems #however button = button( blahblahblha) button.bind("<button-1", somefunction)  print fruit  #yields nothing  mainwin.mainloop() 

this abridged example. else in program works fine, can track variable throughout program, when it's time saved later use, gets erased.

for example, can print variable pass along 1 function argument, , fine. preserved, , prints. instant try loop or store later use, gets lost or overwritten (i'm not quite sure which).

i unfamiliar python, bet it's simple i've missed. assuming supposed work every other language, save string global variable, , stay there until or resets or overwrites it.

my current workaround create text file , save string in until need it.

i using python 2.7.11 on windows 7, have had same issue on ubuntu.

when fruit = 'anything' inside function, assigns local variable. when function ends, local variable disappears. if want reassign global variable, need indicate you'd global keyword.

def somefunction(event):     global fruit # add     blahblahblah     fruit = 'apples'     return fruit 

note functions can access global variables without line, if want assignment same name apply global 1 have include it.

also, "<button-1" should "<button-1>".

also, instead of binding button, should add command it:

button = button(mainwin, text='blahblah', command=somefunction) 

and button widgets, when clicked, don't send event object function they're bound to, define somefunction def somefunction():.

also, print fruit executed once. if want change fruit , see new value, you'll have print point after you've done reassignment. using return send value button doesn't anything, widget can't it. why tkinter apps commonly created object-oriented (oo) programs, can save instance variables without having use global.


Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -