简体   繁体   中英

How to make a tkinter button run another python file

I'm working on a database GUI in tkinter but whenever I try to nest some functions inside one another it always makes unpredictable problems, So I'd like to ask if it's possible to make a button run a function that checks for a condition and if it's true it runs another script.py file that opens another window. Is that possible

I've already tried to press them into one file but weird problems appear and the file is too big to post here so I'm looking for a simpler solution

I'm a beginner so I'm not a hundred percent certain but I think it would look something like this

from tkinter import *
if name.get() == user_name AND pword.get() == password:
    r = Tk()
    my_btn = Button(r, text= "submit",command = open_py)
    my_btn.grid(row=0,column=0)
    r.mainloop()

Is this kind of thing possible or not. How would "open_py():" look like

You can move the code of the new window to a different python file and import it.

For example:

import tkinter as tk

def open_dialog():
    root = tk.Tk()
    button = tk.Text(root, text="Hello!")
    button.pack(root)

    root.mainloop()


if __name__ == "__main__":
    open_dialog()

in hello_dialog.py

import tkinter as tk
from hello_dialog import open_dialog

def main():
    root = tk.Tk()
    button = tk.Button(root, text="Start!", command=open_dialog)
    button.pack(root)

    root.mainloop()

in main.py

Both files need to be in the same folder. You can run main.py and it will run just fine even though the code for the Button showing "Hello." is in a different file, All python files are libraries that you can import functions. classes and variables from. By adding if __name__ == "__main__" you can test whether your function was started directly or if it was imported by another program. To learn more about __name__ and importing other python files take a look at What does if __name__ == "__main__": do? .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM