Python: How to change data type and override a variable from imported module


Python: How to change data type and override a variable from imported module



I have two python programs in same folder named main.py and tk_version.py
I am importing main.py in tk_version.py
I have a variable in main.py which has default value lets say 'xyz'
Now in tk_version.py I am taking the value for the variable from user using Tkinter GUI.



So what I want is when main.py is executed the constant value must be taken and when tk_version.py is executed the value given by user override the default value.



Example:



main.py


var="default"
def show():
print(var)
if __name__ == '__main__':
show()



tk_version.py


from tkinter import *

import main

Main = Tk()

var= StringVar()
def e1chk():
global var
var = e1.get()
main.show()
return


e1=Entry(Main,textvariable=var,width=50)

e1.grid(row=0,column=5,sticky=NSEW)

b1=Button(Main,text="Save",command=e1chk)
b1.grid(row=0,column=8,sticky=NSEW)
Main.mainloop()



OUTPUT for main.py


>>>
=============== RESTART: C:/Users/Gupta Niwas/Desktop/main.py ===============
default
>>>



OUTPUT for tk_version.py (I have entered "abc" in Entry box)


>>>
============ RESTART: C:/Users/Gupta Niwas/Desktop/tk_version.py ============
default
>>>



I want variable to be StringVar to control the entry box values.





The var in tk_version.py is entirely unrelated to the var in main.py - global in Python means "global to this module", not "global everywhere". After having done import main, main.var will refer to its variable.
– jasonharper
Jun 30 at 18:35


var


var


global


import main


main.var





Is there a reason you can't call show with an argument (even if just in one of the two cases, and the other uses a default)?
– jedwards
Jun 30 at 18:56





@jedwards can't pass parameters
– user8810517
Jul 1 at 8:55




1 Answer
1



Just add main. before your variable name.


main.



tk_version.py


tk_version.py


from tkinter import *

import main

Main = Tk()

main.var = StringVar()


def e1chk():
main.var = e1.get()
main.show()
return


e1 = Entry(Main, textvariable=main.var, width=50)

e1.grid(row=0, column=5, sticky=NSEW)

b1 = Button(Main, text="Save", command=e1chk)
b1.grid(row=0, column=8, sticky=NSEW)
Main.mainloop()



Output:


abc
>>>





I want variable to be StringVar to control the entry box values.
– user8810517
Jun 30 at 18:51





I edited the code to do so. @user8810517
– Blincer
Jun 30 at 18:55







By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

List of Kim Possible characters

Audio Livestreaming with Python & Flask

NSwag: Generate C# Client from multiple Versions of an API