Importing module when tkitner button is pressed - python

I have a program which involves several classes as frames in tkinter. I have a separate file that uses pygame and is a chess game. I want to be able to load this file up and execute it when I press a certain tkinter button in one of the frames and to then close this file. I am aware that importing the module at the beginning of the tkinter file runs it immediately which is not what I need. I only want it to run when the button is pressed.
I have attempted to use other modules which do not work. I have tried using functions which also did not work.
I expect to be able to run the chess file when the button is pressed, instead of immediately as this holding file is ran.
However, when run the chess file executes immediately and this other file does not even run.

If you want to open the file in the native editor, the same as double clicking on windows,
you could call os.startfile(file). That runs the file.
Example:
os.startfile('C:\\Windows\\System32\\notepad.exe')
That would run notepad.

Although I wouldn't recommend doing so, you can make a function that will import a module after you press the button as follows:
Button(command=my_func)
def my_func():
import foo, bar
However, if you simply do not wish to run functions from a foreign file, put the following code in the file:
if __name__ == "__main__:
<Code that gets run>
And simply call the function you wish to call:
import bar
bar.foo()
Note that importlib is the better option for importing external files.

If you enclose your main Python code in if __name__ == "__main__":, then it will run only if the file is executed, not loaded as the module. It's a common practice.
And if you make your spam.py like that:
def main():
do_things_here
if __name__ == "__main__":
main()
You can just import spam at the beginning with nothing happening and do spam.main() when you want to execute it.
But if you really want to load modules dynamically, exec("import " + module_name)

Related

Python Question about running multiple scripts in one script

I have couple questions regarding running code from multiple files from one .py file
When I import the Files with
from [subfolder] import [First scriptname - without .py]
from [subfolder] import [Second scriptname - without .py]
the scripts start running instantly, like if my scripts have a print code it would look like this after running the combined-scripts file
print("Hi Im Script One")
print("Hi Im Script Two")
now I could put them in functions and run the functions but my files also have some variables that are not inside functions, the question I have is if there is a way to not start the script automatically after import?
Also what happens with variables inside these scripts, are they usable throughout the combined file or do i need to state them with something like "global"?
is there a way to not start the script automaticly after import?
This is what python's if __name__ == "__main__": is for.
Anything outside that (imports, etc.) will be run when the .py file is imported.
what happens with variables inside these scripts, are they usable troughout the combined file or do i need to state them with something like "global"?
They may be best put inside a class, or you can also (not sure how Pythonic/not this is):
from [FirstScriptName_without_.py] import [className_a], [functionName_b], [varName_c]

How do I get two modules to run after each other?

I'm trying to import two modules so that they run after each other. Here is my code:
from Game import *
main()
from Typing_Question_Screen import *
When I run my code, the Game module loads first but if I close the file, the Typing_Question_Screen module is loaded too. But once the Game module finishes, nothing loads next.
How can I run these two right after each other so that when the Game file ends, the Typing_Question_Screen loads too? Thank you.
From my understanding you have two files:
file1.py
file2.py
If you want to run file.1py and then run file2.py without having to manually do it, there are multiple ways. I would recommend creating a batch.
So you have your two .py files. You will want to create a new file. Don't worry about the extension. We will take care of that later. Navigate to your terminal at the bottom and type in where python. That is the first thing you will put in the double quotes. The next is where your file1.py file is located. You will do the same for file2.py indicated in picture 5. You can use the pause function to pause the process. So after file1.py and ran you will be promted to start file2.py. If you don't want to be prompted, then just remove the pause. You then need to navigate to your file explore to where the batch file was created. In my case it is here (picture 6). Right click on the batch file and select rename. Add .bat at the end. That will convert it to the batch file. Then when you run it (doubleclick). The two .py files that we set up in the batch will run!
The statements in the global scope of imported modules are executed when they are imported. So, you may consider adding function calls or other desired statements in the global scope. Let me give an example:
Game.py:
def main():
print("game")
main()
Typing_Question_Screen.py:
def test():
print("tqs")
test()
The importing file:
from Game import *
from Typing_Question_Screen import *
print("import complete")
The output of this file would be:
game
tqs
import complete
Note that you can check whether the module is being executed independently. (Please keep in mind that usually the opposite of this behavior is used, and generally imports are not expected to execute code by themselves.)
For example, the below implementation calls main only if the module is being imported:
def test():
print("tqs")
if __name__ != __main__:
test()
__name__, a special variable of the module set by the interpreter, is __main__ when the module is run without being imported.
Also, I would avoid importing with *. Moreover, the imports should be at the top of the importing file, separated from other statements and definitions. See: PEP8 on importing
I think you may modify your code as:
import Game
import Typing_Question_Screen
Game.main()

How can I run a python program in another python program?

I have a two different python programs. How can I run one program in another when I need it (e.g if a certain condition is met)?
I heard that I can do that with import <program name>, but when I do this, the program starts immediately and not when I need it.
You should wrap the code in a function. When you want to run that part of code, just call the function.
file1.py:
def fuc1():
print("run.")
# This is to run fuc1 when you run file1 using "python file1.py"
if __name__ == '__main__':
fuc1()
in file2.py:
from file1 import fuc1
fuc1() # call it when you want to run it
try making the second program into a function in that file and import the function like
from <file-name> import <function>
and call the function when the conditions are met
You can just call the import wherever you need it (not necessarily at the top of the file but in the middle of your code) and wrap it inside an if statement so the import will be called when that condition is fulfilled.

How to run script with a function? (repeatedly)

I have a Python program where a function imports another script and runs it. But the script gets run only the first time the function is called.
def Open_Generator(event):
import PasswordGenerator
Any tips?
*The function is called using a button in a tkinter window
This is by design. You should only import a module once. Trying to import a module more than once will cause Python to re-fetch the module object from the cache, but this won't cause the module's code to execute a second time.
Most well-designed modules won't do anything right away when you import them, or at least won't do anything obviously visible. Generally, if you want a module to do work, you need to call one of its functions.
I'm guessing your PasswordGenerator module has some code at the file-level scope. In other words, it has code that isn't inside a function. Try to move that code into a function. Then you can call that function from Open_Generator.
import PasswordGenerator
def Open_Generator(event):
my_password = PasswordGenerator.generate_password()

Python module seeing a full list as empty in another module

I'm working on a pygame project and have the main engine layed out. The problem is I hit a bug that I just can not seem to figure out. What happens is one module can't read a variable from another module.
It's not that the variable can't be read, it just sees an empty list instead of what it really is.
Instead of posting the entire source code I reproduced the bug in two small snippets that hopefully a skillful python-ist can interpret in his\her head.
Code:
main.py (This is the file that gets run)
import screen
screens = [] #A stack for all the game screens
def current_screen():
#return a reference to the current screen
return screens[-1]
def play():
print'play called'
current_screen().update()
if __name__=='__main__':
screens.append(screen.Screen())
play()
screen.py
import main
class Screen:
def __init__(self):
print'screen made'
def update(self):
print main.screens
#Should have a reference to itself in there
Thanks!
Don't import the main script. When you run the main.py file directly, it becomes the __main__ module. When you then import main, it will find the same file (main.py) but load it a second time, under a different module object (main instead of __main__.)
The solution is to not do this. Don't put things you want to 'export' to other modules in the main script. It won't work right. Put them in a third module. Or, pass them as arguments to the functions and classes you're calling.
The whole point of if __name__=='__main__': is to prevent code from being run when a module is imported. So when you import main from screen, that part isn't run and the list stays empt and play() is never called either.

Categories

Resources