I'm designing a program that will have a main menu with multiple buttons. When clicked, I want the buttons to lead to a Python shell for user input.
This is the main menu code:
from tkinter import *
import os
def main_account_screen():
global main_screen
main_screen = Tk()
main_screen.geometry("300x250")
main_screen.title("Menu Screen")
Label(text="Menu", bg="pink", fg="magenta", width="300", height="2",
font=("Calibri", 13)).pack()
Label(text="").pack()
Button(text="View timetable", height="2", width="30",).pack()
Label(text="").pack()
Button(text="Register/login", height="2", width="30").pack()
main_screen.mainloop()
main_account_screen()
So where/how do I add code to lead these buttons onto a Python shell file?
CodePudding user response:
Assuming that you are working on Linux based or under WSL, the quick short method is to attach calling script functions to the command parameter of the Button widget as follow:
from tkinter import *
import os
def timeTableCallBack():
os.system('python $(pwd)/ViewTimeTable.py')
def loginCallBack():
os.system('python $(pwd)/RegisterLogin.py')
def main_account_screen():
global main_screen
main_screen = Tk()
main_screen.geometry("300x250")
main_screen.title("Menu Screen")
Label(text="Menu", bg="pink", fg="magenta", width="300", height="2",
font=("Calibri", 13)).pack()
Label(text="").pack()
Button(text="View timetable", height="2", width="30",command= timeTableCallBack).pack()
Label(text="").pack()
Button(text="Register/login", height="2", width="30",command= loginCallBack).pack()
main_screen.mainloop()
main_account_screen()
CodePudding user response:
You can do it by defining a function that does what you want and then specifying it via the command=
option when creating the Button
s.
Here's some documentation on what options Button
a have.
In this case the function spawns a separate process running a separate copy of the Python interpreter via the subprocess
module.
import subprocess
import sys
from tkinter import *
def main_account_screen():
global main_screen
main_screen = Tk()
main_screen.geometry("300x250")
main_screen.title("Menu Screen")
Label(text="Menu", bg="pink", fg="magenta", width="300", height="2",
font=("Calibri", 13)).pack()
Label(text="").pack()
Button(text="View timetable", height="2", width="30", command=python_shell).pack()
Label(text="").pack()
Button(text="Register/login", height="2", width="30", command=python_shell).pack()
main_screen.mainloop()
def python_shell():
"""Run Python shell in a separate console."""
subprocess.run(sys.executable, creationflags=subprocess.CREATE_NEW_CONSOLE)
main_account_screen()