7

I was wondering if it is possible (and if so, how) to have the Python Shell output and input inside a tkinter window I have made. I searched on google but I can't seem to find anything. If possible, is there a short version that a beginner could understand. (All the websites I have tried I just could not understand.)

Here is my code that I have got:

from tkinter import *



def Exit():
    print()

def newClassResults():
    #assigns variable to an input so it can be reffered to later
    amount = int(input("How many people would you like to add? "))

    #starts for loop
    for counter in range(amount):
#assigns inputto a  variable called 'newName'
        newName = input("\nEnter the new student's name: ")
#assigns input to a  variable called 'newScore'
        newScore = int(input("Enter the new student's score: "))
#adds new results to the list below
        students_and_score.append((newName,newScore))
        score.append(newScore)

def saveResults():
#imports time module so that the program can pause for a certain amount of time
    import time
    print("\nSaving...")
    import random, decimal
    time1 = decimal.Decimal(random.randrange(1,10))/10
    time.sleep(time1)
    print("\nStudents' names saved")
    print("Students' scores saved")

def sortResults():
#imports operator module 
    import operator
#imports time module 
    import time
    #sorts results in acsending order
    students_and_score.sort(key=operator.itemgetter(1))
#prints in ascending order
    print("\nSorting Results...")
    import random, decimal
    time1 = decimal.Decimal(random.randrange(1,10))/10
    time.sleep(time1)
    print(students_and_score)

def percentageCalc():
#assigns input to variable called 'number'
    number = int(input("\nEnter minimum mark: "))
#creates variable called 'size'
    size = len(score)
    index = 0
    for counter in range(size):
        if score[index] > number:
            higher.append(score[index])
        index = index + 1
    higherLength = len(higher)
#calculates percentage of people with score over amount entered
    finished = higherLength / size
    finished = finished * 100
#rounds percentage
    finished = round(finished)
#creates space between line
    print("\n")
    print(finished,"% of your students got over",number,"marks")

def printResults():
#starts for loop
    for pair in students_and_score:
#creates space between line
        print("\n")
#changes layout of list so it is more readable
        print(pair[0],pair[1])

#assigns list to a variable
students_and_score = [("Imelda Thomas",74),("Craig Parr",90),("Eric     Salisbury",58),("Laurence Mann",35),("Bill Walford",82),("David Haroald",27),("Pamela Langley",43),("Sarah Boat",39),("Rachel Matthews",62),("Michaela Cunningham",69)]
score = [74,90,58,35,82,27,43,39,62,69]
higher = []

window = Tk()
#sets background colour
window.configure(background="white")
#assigns title
window.title("Menu")
#sets the size of window
window.geometry("300x300")
window.wm_iconbitmap('favicon.ico')

menu = Menu(window)


subMenu = Menu(menu)
menu.add_cascade(label="File", menu=subMenu)
subMenu.add_command(label="Exit", command=Exit)

subMenu = Menu(menu)
menu.add_cascade(label="Edit", menu=subMenu)
subMenu.add_command(label="Enter New Class Results",     command=newClassResults)
subMenu.add_separator()
subMenu.add_command(label="Save Results", command=saveResults)
subMenu.add_command(label="Sort Results", command=sortResults)
subMenu.add_command(label="Print Results", command=printResults)
subMenu.add_separator()
subMenu.add_command(label="Calculate Percentage", command=percentageCalc)

#Finishes off
window.config(menu=menu)
window.mainloop()
jcoppens
  • 5,306
  • 6
  • 27
  • 47
AlexDear
  • 83
  • 1
  • 6
  • To show the output, you could use a tkinter `Text` widget and to get the input you could use a `Entry` widget (and eventually a `Button`, even though you don't strictly need it).. One problem that can happen is that, if you have a lot of computions behind the scenes, your GUI could freeze, in that case you could use threads or maybe the `after` function... – nbro May 13 '15 at 18:06
  • So how would I apply the Text widget to my code? – AlexDear May 13 '15 at 20:26
  • Does this answer your question? [build cmd into Tkinter window](https://stackoverflow.com/questions/5999627/build-cmd-into-tkinter-window) – user26742873 Jul 06 '20 at 13:16

3 Answers3

6

Have a look at this post.

The author inserts a terminal emulator in a tkinter window. I've modified the program, inserting the command to start python in the tkinter window:

#!/usr/bin/python

from Tkinter import *
import os

root = Tk()
termf = Frame(root, width = 400, height = 200)

termf.pack(fill=BOTH, expand=YES)
wid = termf.winfo_id()
os.system('xterm -into %d -geometry 80x20 -sb -e python &' % wid)

root.mainloop()

This might not work in Windows though, as there is no xterm.

This is a screenshot of the terminal working, and I packed a button in the same window, just to show the terminal is really in the frame:

enter image description here

Community
  • 1
  • 1
jcoppens
  • 5,306
  • 6
  • 27
  • 47
  • I am still not convinced if this code does what it is supposed to do on a Mac OS X, because what happens to me is that a Python shell section is started on `xterm` and nothing else (and only if I specify the whole path to `xterm`), I am not seeing what you want to achieve with this code... what does this code is supposed to do? For me the emulator is not inserted in the Frame, but it starts independently and an empty tkinter window runs at the same time.. – nbro May 13 '15 at 21:15
  • It may not work on Max OS (I can't test that), but it works in Linux. The poster didn't mention (or tag) if he was using Mac OS. I've added a screenshot of the result. – jcoppens May 13 '15 at 21:56
  • Note: for python3 you need to >apt install python3-tk and the import is: "from tkinter import *" – Jay Marm Apr 09 '21 at 21:10
1

The IDLE editor which is shipped with python actually does exactly this by embedding a python shell in to a Text tkinter widget.

If you locate or download the idlelib sources:

https://github.com/python/cpython/tree/master/Lib/idlelib

you should be able to just run the editor and also inspect/modify the code.

JacobP
  • 561
  • 3
  • 21
0

You could always try to eval(string), capture the output and print it to some textbox.

Josep Valls
  • 5,483
  • 2
  • 33
  • 67