简体   繁体   中英

Can I import a python script to make it run in my GUI?

I was working on a GUI app that I was hoping to use to run a python script inside of it(don't know if it's even possible) but I do not quite understand how can importing the script to my GUI code would be for use, like can I make the script run if I click a button?

GUI:

import tkinter as tk
from tkinter import Button, Canvas, Image, PhotoImage, filedialog, Text
import os
from tkinter.constants import COMMAND, DISABLED

root = tk.Tk()

canvas = tk.Canvas(root, height = 750, width = 800, bg = "#110a60")
canvas.pack()

root.resizable(False, False)
 
frame = tk.Frame(root, bg = "black")
frame.place(relheight = 0.8, relwidth = 0.8, relx = 0.1, rely = 0.1)

start_button = Button(root, text = 'Start Program', padx = 10, pady = 5, fg = "#FFFF00", bg = "#012456", state = DISABLED)
start_button.place(x = 350, y = 680)

exit_button = Button(root, text = 'Exit', padx = 20, pady = 5, fg = "#FFFF00", bg = "#012456", command = exit)
exit_button.place(x = 368, y = 714.5 )

root.mainloop()

let's say the script is called a program.py can I import it and make it run inside the canvas when I click the start program button

import program

I have tried doing this:

import tkinter as tk
from tkinter import Button, Canvas, Image, PhotoImage, filedialog, Text
import os
from tkinter.constants import COMMAND, DISABLED

def script():
    os.startfile('[path]program.py')

root = tk.Tk()

canvas = tk.Canvas(root, height = 750, width = 800, bg = "#110a60")
canvas.pack()

root.resizable(False, False)

frame = tk.Frame(root, bg = "black")
frame.place(relheight = 0.8, relwidth = 0.8, relx = 0.1, rely = 0.1)

start_button = Button(root, text = 'Start Program', padx = 10, pady = 5, fg = "#FFFF00", bg = "#012456", command = script)
start_button.place(x = 350, y = 680)

exit_button = Button(root, text = 'Exit', padx = 20, pady = 5, fg = "#FFFF00", bg = "#012456", command = exit)
exit_button.place(x = 368, y = 714.5 )

root.mainloop()

But this only runs the script in another window, I want it to run inside the canvas I made in other means I want the text outputting from the script to be printed inside the canvas and every user input to be made inside the canvas

So everything my script does displays in my GUI I am making inside the canvas

Import your script (program.py in the same directory as the main file) in your header

from program import function

then just call the function as tkinter button command

start_button = Button(root, text = 'Start Program', padx = 10, pady = 5, fg = "#FFFF00", bg = "#012456", command = function)

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