Home > Net >  How to change variable in another python file?
How to change variable in another python file?

Time:12-22

I have two python files. In this example I have made it really simple, File_A and File_B. In File_A I want to define a variable, and in File_B I want to use this variable to do something. The code is a bit more complex, but this is the idea:

FileA:

import tkinter as tk


window = tk.Tk()
entry = tk.Entry(window)
entry.pack()
button = tk.Button(window, text="Click me!", command=lambda: on_button_click(entry.get()))
button.pack()

def on_button_click(ip):
    pass
  #changing variable in File_B to 'ip'
  #run File_B

window.mainloop()

File_B:

print(value) #value entered in File_A

I have tried things in File_B like:

From File_A import value

But this didn't seem to work for me, or it made the GUI open once more.

Does anyone have a suggestion?

CodePudding user response:

You can wrap the file's code with a function instead, and pass relevant variables using the function parameters.

TestB:

def main(ip):
    print(ip)
    
    <rest of code for file TestB>

TestA:

import TestB

def on_button_click(ip):
    TestB.main(ip)

Maybe add more details to your question (what are you trying to do?), there might be a more efficient way to solve this problem.

  • Related