I am new in creating GUI. I am doing it in Python with Tkinter. In my program I calculate following characteristics
def my_myfunction():
my code ...
print("Centroid:", centroid_x, centroid_y)
print("Area:", area)
print("Angle:", angle)
I would like to ask for any help/tips how to display those values in GUI window or how to save them in .txt file so that I can call them in my GUI
Thanks in advance
Tkinter is easy and an easy way to do a GUI, but sometimes it can be frustrating. But you should have read the docs before.
However, you can do in this way.
from tkinter import *
yourData = "My text here"
root = Tk()
frame = Frame(root, width=100, height=100)
frame.pack()
lab = Label(frame,text=yourData)
lab.pack()
root.mainloop()
There are several ways to display the results of any operation in tkiner.
You can use Label, Entry, Text, or even pop up messages boxes. There are some other options but these will probably be what you are looking for.
Take a look at the below example.
I have a simple adding program that will take 2 numbers and add them together. It will display the results in each kind of field you can use as an output in tkinter.
import tkinter as tk
from tkinter import messagebox
class App(tk.Frame):
def __init__(self, master):
self.master = master
lbl1 = tk.Label(self.master, text = "Enter 2 numbers to be added \ntogether and click submit")
lbl1.grid(row = 0, column = 0, columnspan = 3)
self.entry1 = tk.Entry(self.master, width = 5)
self.entry1.grid(row = 1, column = 0)
self.lbl2 = tk.Label(self.master, text = "+")
self.lbl2.grid(row = 1, column = 1)
self.entry2 = tk.Entry(self.master, width = 5)
self.entry2.grid(row = 1, column = 2)
btn1 = tk.Button(self.master, text = "Submit", command = self.add_numbers)
btn1.grid(row = 2, column = 1)
self.lbl3 = tk.Label(self.master, text = "Sum = ")
self.lbl3.grid(row = 3, column = 1)
self.entry3 = tk.Entry(self.master, width = 10)
self.entry3.grid(row = 4, column = 1)
self.text1 = tk.Text(self.master, height = 1, width = 10)
self.text1.grid(row = 5, column = 1)
def add_numbers(self):
x = self.entry1.get()
y = self.entry2.get()
if x != "" and y != "":
sumxy = int(x) + int(y)
self.lbl3.config(text = "Sum = {}".format(sumxy))
self.entry3.delete(0, "end")
self.entry3.insert(0, sumxy)
self.text1.delete(1.0, "end")
self.text1.insert(1.0, sumxy)
messagebox.showinfo("Sum of {} and {}".format(x,y),
"Sum of {} and {} = {}".format(x, y, sumxy))
if __name__ == "__main__":
root = tk.Tk()
myapp = App(root)
root.mainloop()
Related
I have written a code for a basic game but the image and shape don't show up unless I add something like item.pack() or win.mainloop() [which doesn't really make sense] but then the lines below it don't run.
When I don't have anything, the buttons show up but the image doesn't show up.
import tkinter as tk
import random
from tkinter import messagebox
win = tk.Tk()
my_label = tk.Label(win, text="Color of the Baloon Game")
my_label.pack()
my_canvas = tk.Canvas(win, width=400, height=600)
my_canvas.pack()
background_image=tk.PhotoImage(file = "CS_Game_menu.png")
background_label = tk.Label(my_canvas, image=background_image)
background_label.photo = background_image
background_label.grid(row = 0, rowspan = 10, column = 0, columnspan = 10)
def drawCircle():
color = "green"
x1 = 265
y1 = 80
diameter = 90
my_canvas.destroy()
circle_button.destroy()
quit_button.destroy()
my_label.destroy()
my_label1 = tk.Label(win, text="What is the Color of the Baloon?", font="Purisa")
my_label1.pack()
my_canvas1 = tk.Canvas(win, width=400, height=600)
my_canvas1.pack()
image1 = r"CS_Game_baloon.png"
photo1 = tk.PhotoImage(file=image1)
item = my_canvas1.create_image(200, 350, image=photo1)
shape = my_canvas1.create_oval(x1, y1, x1 + diameter, y1 + diameter+20, fill=color)
item.pack()
game1_button = tk.Button(my_canvas1, text = "Green")
game1_button.grid(row= 8, column = 3)
game1_button["command"] = lambda: messagebox.showinfo("Congratulations!", "Correct Answer!")
game2_button = tk.Button(my_canvas1, text = "Blue")
game2_button.grid(row= 8, column = 5)
game2_button["command"] = lambda: messagebox.showinfo("Sorry!", "Incorrect Answer!")
game3_button = tk.Button(my_canvas1, text = "Red")
game3_button.grid(row= 8, column = 7)
game3_button["command"] = lambda: messagebox.showinfo("Sorry", "Incorrect Answer!")
circle_button = tk.Button(win, text="New Game")
circle_button.pack()
circle_button["command"] = drawCircle
quit_button = tk.Button(win, text="Quit")
quit_button.pack()
quit_button['command'] = win.destroy
You are using both the create_... methods and grid methods on your canvas object. It won't behave as you expected.
To achieve what you want, you can create a Frame, put your buttons in it, and then use create_window method on your canvas:
def drawCircle():
...
shape = my_canvas1.create_oval(x1, y1, x1 + diameter, y1 + diameter+20, fill=color)
frame = tk.Frame(my_canvas1)
game1_button = tk.Button(frame, text = "Green")
game1_button.grid(row= 8, column = 3)
game1_button["command"] = lambda: messagebox.showinfo("Congratulations!", "Correct Answer!")
game2_button = tk.Button(frame, text = "Blue")
game2_button.grid(row= 8, column = 5)
game2_button["command"] = lambda: messagebox.showinfo("Sorry!", "Incorrect Answer!")
game3_button = tk.Button(frame, text = "Red")
game3_button.grid(row= 8, column = 7)
game3_button["command"] = lambda: messagebox.showinfo("Sorry", "Incorrect Answer!")
my_canvas1.create_window(200,500,window=frame)
And of course, add win.mainloop() to the bottom of your program if you haven't already.
I was really curious why I cannot get my add_button to work,
as the window fails to come up when creating it.
from tkinter import *
class Calculator:
#-------------------------------------------------
def __init__(self, master):
self.master = master
master.title("Calculator")
self.close_button = Button(master, text = "Close", command = master.destroy)
Label(master, text = "First Digit").grid(row = 0)
Label(master, text = "Second Digit").grid(row = 1)
self.input1 = 0
self.input2 = 0
input1 = Entry(master)
input2 = Entry(master)
input1.grid(row = 0, column = 1)
input2.grid(row = 1, column = 1)
self.close_button.grid(row = 2, column = 0)
self.add_buton = Button(master, text = "Add", command = self.add())
self.add_button.grid(row = 2, column = 1)
master.configure(background = 'grey')
return
#-------------------------------------------------
def add(self):
return self.input1.get() + self.input2.get()
#-------------------------------------------------
#-------------------------------------------------
root = Tk()
calc = Calculator(root)
root.mainloop()
#-------------------------------------------------
Welcome to Stack!
I've looked through you code I've been able to do what you are asking. There were a few errors within your code:
a) you had self.add_buton and self.add_button which caused an error.
b) self.input1 = 0 and self.input2 = 0 are not required.
c) You were calling self.add() as the command and you should be calling self.add. When calling it as a command you do not need ()
d)input1 = Entry(master) should be self.input1 = tk.Entry(master)
e) You should convert your input values into int or float as otherwise it will just one value onto the end of the other. (Eg, 1 + 5 = 15 whereas int(1) + int(5) = 6
Here is your code with the entry boxes working as they should. I have import tkinter as tk hence why it is tk.Entry
from tkinter import *
import tkinter as tk
class Calculator:
#-------------------------------------------------
def __init__(self, master):
self.master = master
master.title("Calculator")
self.close_button = Button(master, text = "Close", command = master.destroy)
Label(master, text = "First Digit").grid(row = 0)
Label(master, text = "Second Digit").grid(row = 1)
self.input1 = tk.Entry(bd=5, width=35, background='gray35', foreground='snow')
self.input2 = tk.Entry(bd=5, width=35, background='gray35', foreground='snow')
self.input1.grid(row = 0, column = 1)
self.input2.grid(row = 1, column = 1)
self.close_button.grid(row = 2, column = 0)
self.add_button = tk.Button(master, text = "Add", command = self.add)
self.add_button.grid(row = 2, column = 1)
master.configure(background = 'grey')
return
#-------------------------------------------------
def add(self):
val = self.input1.get()
print(val)
#-------------------------------------------------
#-------------------------------------------------
root = Tk()
calc = Calculator(root)
root.mainloop()
This should now work how you wanted it too. The variables within the entry can be changed to suit. You were correct in calling the value of the entry with self.input1.get().
Hope this has helped.
I've a Tkinter-programm where I regularly (10 times/second) update Labels with certain sensor-values.
The problem is that they are arranged with .grid right next to each other and when a value gets/loses a place (e.g. 10 -> 9, 60 -> 150, you see the number needs extra space) the label jumps back and forth (because the number gains or loses a space and therefore .grid responds by adjusting the Label).
How can i avoid that? Do I need to change Text & Numbers to a certain font or is there a function that fixes the Labels place? I'd be happy about useful answers.
Here's a code example (please notice how the labels are adjusting cause that's the problem):
#!/usr/bin/env
import sys
import time
import subprocess
from Tkinter import *
import numpy
import random
i = 0
x = 0
def GetValue():
x = random.randint(0,10000)
time.sleep(0.1)
return x
def UebergabeTkinter():
while 1:
CompleteValue = GetValue()
Variable1.set(CompleteValue)
Variable2.set(CompleteValue)
Variable3.set(CompleteValue)
Variable4.set(CompleteValue)
root.update()
def Exit():
root.destroy()
return
try:
root = Tk()
Leiste = Menu(root)
root.config(menu = Leiste)
DateiMenu = Menu(Leiste)
Leiste.add_cascade(label = "datei", menu = DateiMenu)
DateiMenu.add_command(label = "Exit", command = Exit)
EditMenu = Menu(Leiste)
Leiste.add_cascade(label = "edit", menu = EditMenu)
Variable1 = IntVar()
Variable2 = IntVar()
Variable3 = IntVar()
Variable4 = IntVar()
Ausgang = 0
for column in range(0,8,2):
String1 = "Ausgang "
String1 += `Ausgang`
Ausgang = Ausgang + 1
Label(text = String1).grid(row=0,column=column)
Ausgang = 0
for column in range(0,8,2):
String1 = "Der Wert von "
String2 = " ist: "
String1 += `Ausgang`
Ausgang = Ausgang + 1
String3 = String1+String2
Label(text = String3).grid(row=2,column=column)
Label1 = Label(root, textvariable = Variable1)
Label1.grid(row = 2, column = 1, sticky = W+E+N+S)
Label2 = Label(root, textvariable = Variable2)
Label2.grid(row = 2, column = 3, sticky = W+E+N+S)
Label3 = Label(root, textvariable = Variable3)
Label3.grid(row = 2, column = 5, sticky = W+E+N+S)
Label4 = Label(root, textvariable = Variable4)
Label4.grid(row = 2, column = 7, sticky = W+E+N+S)
UebergabeTkinter()
root.mainloop()
except KeyboardInterrupt:
print "Hallo"
You can give labels a fixed width:
Label1 = Label(root, textvariable=Variable1, width=4)
Just make sure they are large enough to fit every number that could be put in, since of course next no the label not shrinking when the number is shorter, this also means that they will not grow to fit larger numbers.
I'm a 11th grader (5th year student) that just started studying Python programming. I am trying to make a GUI where I can chose what shape I want to draw with turtle and input the values needed to draw out the shape. I managed to do that with the following code (where I already did the functions of the turtle fractals and imported that file):
from tkinter import *
import turtlegraphics
from turtle import *
import math
#set up the window
root = Tk()
root.title('Turtle shapes')
root.geometry('300x200+100+100')
#make the interface
turtleLabel = Label(root, text = 'Turtle Fractals Generator')
turtleLabel.grid(row = 0, column =1, columnspan =2)
#order widgets
orderLabel = Label(root, text ='Order')
orderLabel.grid(row = 1, column =0)
orderStr = StringVar()
orderEntry = Entry(root, textvariable = orderStr)
orderEntry.grid(row = 1, column = 1, columnspan = 2)
#length widgets
lengthLabel = Label(root, text ='Length')
lengthLabel.grid(row = 2, column =0)
lengthStr = StringVar()
lengthEntry = Entry(root, textvariable = lengthStr)
lengthEntry.grid(row = 2, column = 1, columnspan = 2)
#button widgets
def clearF():
#Clear the entries
orderStr.set('')
lengthStr.set('')
return
#end def
clearButton = Button(root, text ='Clear', command = clearF)
clearButton.grid(row = 3, column =1)
def treeF():
order = int(orderStr.get())
length = float(lengthStr.get())
turtlegraphics.tree(order,length, pen)
return
#end def
treeButton = Button(root, text ='Tree', command = treeF)
treeButton.grid(row = 1, column =3)
#make a gasket button
def gasketF():
order = int(orderStr.get())
length = float(lengthStr.get())
turtlegraphics.gasket(order,length,pen)
return
#end def
gasButton = Button(root, text ='Gasket', command = gasketF)
gasButton.grid(row = 2, column =3)
#make a dandelion button
def dandelionF():
order = int(orderStr.get())
length = float(lengthStr.get())
turtlegraphics.tree4(order,length,pen)
return
#end def
danButton = Button(root, text ='Dandelion', command = dandelionF)
danButton.grid(row = 3, column =3)
#make flalke button
def kevinF():
order = int(orderStr.get())
length = float(lengthStr.get())
turtlegraphics.k(order,length,pen)
return
#end def
def flakeF():
order = int(orderStr.get())
length = float(lengthStr.get())
turtlegraphics.flake(order,length,pen)
return
#end def
flakeButton = Button(root, text ='Flake', command = flakeF)
flakeButton.grid(row = 4, column =3)
#make a screen and a pen
pen = Pen()
screen = Screen()
pen.speed(0)
pen.color('blue')
pen.width(3)
screen.bgcolor('white')
root.mainloop()
However, I want to try and put a list to chose the shape from rather than having several buttons. I don't understand much about lists due to the fact that I wasn't taught it yet but after doing research this is what I got:
'''
program gui to draw turtle fractals
'''
from tkinter import *
import turtlegraphics
from turtle import *
import math
#make a screen and a pen
pen = Pen()
def treeF():
order = int(orderStr.get())
length = float(lengthStr.get())
turtlegraphics.tree(order,length, pen)
return
#end def
#make a gasket button
def gasketF():
order = int(orderStr.get())
length = float(lengthStr.get())
turtlegraphics.gasket(order,length,pen)
return
#end def
#make a dandelion button
def dandelionF():
order = int(orderStr.get())
length = float(lengthStr.get())
turtlegraphics.tree4(order,length,pen)
return
#end def
#make flalke button
def kevinF():
order = int(orderStr.get())
length = float(lengthStr.get())
turtlegraphics.k(order,length,pen)
return
#end def
def flakeF():
order = int(orderStr.get())
length = float(lengthStr.get())
turtlegraphics.flake(order,length,pen)
return
#end def
screen = Screen()
pen.speed(0)
pen.color('blue')
pen.width(3)
screen.bgcolor('white')
#set up the window
root = Tk()
root.title('turtle shapes')
root.geometry('600x300+100+100')
#make the interface
turtleLabel = Label(root, text = 'Turtle Fractals Generator')
turtleLabel.grid(row = 0, column =1, columnspan =2)
#order widgets
orderLabel = Label(root, text ='Order')
orderLabel.grid(row = 1, column =0)
orderStr = StringVar()
orderEntry = Entry(root, textvariable = orderStr)
orderEntry.grid(row = 1, column = 1, columnspan = 2)
#length widgets
lengthLabel = Label(root, text ='Length')
lengthLabel.grid(row = 2, column =0)
lengthStr = StringVar()
lengthEntry = Entry(root, textvariable = lengthStr)
lengthEntry.grid(row = 2, column = 1, columnspan = 2)
#button widgets
def clearF():
#Clear the entries
orderStr.set('')
lengthStr.set('')
return
#end def
clearButton = Button(root, text ='Clear', command = clearF)
clearButton.grid(row = 3, column =1)
#list
def selection():
obj = nameList.curselection()[0]
if obj == 'tree':
command = treeF
return
if obj == 'dandelion':
command = dandelionF
return
if obj == 'flake':
command = flakeF
return
if obj == 'gasketF':
command = gasketF
return
#end if
#end def
#create list
listbox = Listbox(root,selectmode = SINGLE) #select mode is type of
selection
listButton= Button(root, text = 'chose fractal')
labelVar = StringVar()
nameLabel = Label(root, textvariable = labelVar)
nameLabel.grid(row = 2 , column = 7, columnspan = 2)
labelVar.set('choose a fractal')
names = ['tree','dandelion','flake','gasket']
nameList = Listbox(root)
for i in names:
nameList.insert(END, i)
nameList.grid(row = 4, column =7, columnspan = 2)
selectionButton = Button(root, text = 'draw', command = selection)
selectionButton.grid(row = 5, column = 7, columnspan = 2)
root.mainloop()
I know something is wrong with my code, but I can't tell what I did wrong. When I run my code I get no error whatsoever, but it does not draw the shape. In addition, the clear button does not do its function when clicked. How can I can I fix this?
Your immediate problem is how selection() works -- it was comparing numbers to strings and have the code necessary to execute any of the subprograms. I've reworked it below to get the behavior you desire. I've also made other changes and simplifications:
from tkinter import *
from turtle import Pen, Screen
import turtlegraphics
def treeF():
order = int(orderEntry.get())
length = float(lengthEntry.get())
turtlegraphics.tree(order, length, pen)
def dandelionF():
order = int(orderEntry.get())
length = float(lengthEntry.get())
turtlegraphics.tree4(order, length, pen)
def flakeF():
order = int(orderEntry.get())
length = float(lengthEntry.get())
turtlegraphics.flake(order, length, pen)
def gasketF():
order = int(orderEntry.get())
length = float(lengthEntry.get())
turtlegraphics.gasket(order, length, pen)
def kevinF():
order = int(orderEntry.get())
length = float(lengthEntry.get())
turtlegraphics.k(order, length, pen)
fractals = [('tree', treeF), ('dandelion', dandelionF), ('flake', flakeF), ('gasket', gasketF), ('kevin', kevinF)]
# make a screen and a pen
screen = Screen()
screen.bgcolor('white')
pen = Pen()
pen.speed('fastest')
pen.color('blue')
pen.width(3)
# set up the window
root = Tk()
root.title('turtle shapes')
root.geometry('600x400+100+100')
# make the interface
turtleLabel = Label(root, text='Turtle Fractals Generator')
turtleLabel.grid(row=0, column=1, columnspan=2)
# order widgets
orderLabel = Label(root, text='Order')
orderLabel.grid(row=1, column=0)
orderEntry = Entry(root)
orderEntry.grid(row=1, column=1, columnspan=2)
# length widgets
lengthLabel = Label(root, text='Length')
lengthLabel.grid(row=2, column=0)
lengthEntry = Entry(root)
lengthEntry.grid(row=2, column=1, columnspan=2)
# button widgets
def clearF():
# Clear the entries
orderEntry.delete(0, 'end')
lengthEntry.delete(0, 'end')
clearButton = Button(root, text='Clear', command=clearF)
clearButton.grid(row=3, column=1)
# list
def selection():
selections = nameList.curselection()
if selections:
selection = selections[0]
if selection < len(fractals):
name, definition = fractals[selection]
definition()
# create list
listbox = Listbox(root, selectmode=SINGLE) # select mode is type of selection
listButton = Button(root, text='chose fractal')
labelVar = StringVar()
nameLabel = Label(root, textvariable=labelVar)
nameLabel.grid(row=2, column=7, columnspan=2)
labelVar.set('choose a fractal')
nameList = Listbox(root)
for name, definition in fractals:
nameList.insert(END, name)
nameList.grid(row=4, column=7, columnspan=2)
selectionButton = Button(root, text='Draw', command=selection)
selectionButton.grid(row=5, column=7, columnspan=2)
root.mainloop()
General comments about your code:
Find and follow a good Python coding style -- it makes understanding your code more difficult when you invent your own coding "style".
This isn't the correct way to integrate turtle with tkinter. Search StackOverflow, or the turtle documentation, for RawTurtle and TurtleScreen, the classes you use instead of Turtle (aka Pen) and Screen when embedding in an existing Tk window structure.
I am using a mix of Tkinter and graphics.py (a wrapper on Tkinter) to create a fairly basic integrator (find the area under a graph) with a GUI. As of now, the main "control panel" for the integrator is separate from the actual graph (which is made by using graphics.py). I am using Tkinter's Radiobutton() for the choice selection of the integration type (Left Rectangular, Right Rectangular, Trapezoidal, or Simpson's Approximation).
My problem is that I am unable to get the output from the radiobuttons. I was using the example from TutorialsPoint: Tkinter Radiobutton.
Here is my code:
class FunctionInput:
def __init__(self, master, window, items):
self.window = window
self.items = items
self.runProgram = True
self.typeChoice = tk.StringVar()
self.frame = tk.Frame(master)
self.typeFrame = tk.Frame(self.frame)
self.quitButton = tk.Button(self.frame, text = 'Quit', command = self.frame.quit)
self.optLabel = tk.Label(self.frame, text = 'Type of Approximation: ')
self.optL = tk.Radiobutton(self.typeFrame, text = 'Left Rectangular', variable = self.typeChoice, value = 'l')
self.optR = tk.Radiobutton(self.typeFrame, text = 'Right Rectangular', variable = self.typeChoice, value = 'r')
self.optT = tk.Radiobutton(self.typeFrame, text = 'Trapezoidal', variable = self.typeChoice, value = 't')
self.optS = tk.Radiobutton(self.typeFrame, text = 'Simpsons Rule', variable = self.typeChoice, value = 's')
self.optL.grid(row = 1, column = 1, padx = 5, pady = 5)
self.optR.grid(row = 1, column = 2, padx = 5, pady = 5)
self.optT.grid(row = 2, column = 1, padx = 5, pady = 5)
self.optS.grid(row = 2, column = 2, padx = 5, pady = 5)
self.optLabel.grid(row = 4)
self.typeFrame.grid(row = 5)
self.quitButton.grid(row = 6)
# there were numerous other widgets and frames, but I only included the relevant ones
self.frame.grid()
def getInput(self):
type_integration = self.typeChoice.get()
self.frame.quit()
return type_integration
def main():
# some other code, win and axisLabels are defined prior to this
root = tk.Tk(className = ' Function Grapher')
app = FunctionInput(root, win, axisLabels)
root.rowconfigure(0, weight = 1)
root.columnconfigure(0, weight = 1)
root.mainloop() # there is a button to exit the mainloop in my GUI
typeIntegration = app.getInput()
print typeIntegration # trying to debug it
if __name__ == '__main__': main()
However, it doesn't not print the variable. It prints an empty string, so execution is not a problem. root.mainloop() does not get stuck in an infinite loop, because I have a button in my GUI (not shown here because it is irrelevant) that exits it. An error is not raised, so I'm guessing that the issue is with setting the option to the variable. Any help is greatly appreciated.
Also, on a side note, whenever I run the program, the 'Right Rectangular', 'Trapezoidal', and 'Simpson's Rule' radiobuttons are grayed out, like such:
This grayness goes away if I click on one of the radiobuttons, but until then, it stays. If there is some way to fix this, please let me know.
Thanks!
I haven't seen the part of the exit button, but your code does something like this:
Starts the mainloop
The event handler of the exit button calls root.quit()
In getInput, retrieves the value and calls self.frame.quit()
Calling Tkinter functions after the mainloop may lead to problems like this, so you should get the value of the StringVar first and then exit the GUI loop. This is a working example based on your code:
import Tkinter as tk
class App():
def __init__(self, master):
self.master = master
self.type_integration = None
self.typeChoice = tk.StringVar()
self.typeChoice.set(None) # This fixes the grayness of the radio buttons!
self.typeFrame = tk.Frame(master)
OPTIONS = [('Left Rectangular', 'l'),
('Right Rectangular', 'r'),
('Trapezoidal', 't'),
('Simpsons Rule', 's')]
for text, value in OPTIONS:
tk.Radiobutton(self.typeFrame, text=text, variable=self.typeChoice, value=value).pack()
tk.Button(self.typeFrame, text="Exit", command=self.exit).pack()
self.typeFrame.pack()
def exit(self):
self.type_integration = self.typeChoice.get()
self.master.destroy() # self.master.quit() freezes the GUI
def getinput(self):
return self.type_integration
master = tk.Tk()
app = App(master)
tk.mainloop()
print app.getinput()
The problem was that since I was using multiple other widgets, I had to set StringVar()s master parameter as self.typeFrame:
class FunctionInput:
def __init__(self, master, window, items):
self.window = window
self.items = items
self.runProgram = True
self.frame = tk.Frame(master)
self.typeFrame = tk.Frame(self.frame)
self.typeChoice = tk.StringVar(self.typeFrame)
self.quitButton = tk.Button(self.frame, text = 'Quit', command = self.frame.quit)
self.optLabel = tk.Label(self.frame, text = 'Type of Approximation: ')
self.optL = tk.Radiobutton(self.typeFrame, text = 'Left Rectangular', variable = self.typeChoice, value = 'l')
self.optR = tk.Radiobutton(self.typeFrame, text = 'Right Rectangular', variable = self.typeChoice, value = 'r')
self.optT = tk.Radiobutton(self.typeFrame, text = 'Trapezoidal', variable = self.typeChoice, value = 't')
self.optS = tk.Radiobutton(self.typeFrame, text = 'Simpsons Rule', variable = self.typeChoice, value = 's')
self.optL.grid(row = 1, column = 1, padx = 5, pady = 5)
self.optR.grid(row = 1, column = 2, padx = 5, pady = 5)
self.optT.grid(row = 2, column = 1, padx = 5, pady = 5)
self.optS.grid(row = 2, column = 2, padx = 5, pady = 5)
self.optLabel.grid(row = 4)
self.typeFrame.grid(row = 5)
self.quitButton.grid(row = 6)
# there were numerous other widgets and frames, but I only included the relevant ones
self.frame.grid()
def getInput(self):
type_integration = self.typeChoice.get()
self.frame.quit()
return type_integration
def main():
# some other code, win and axisLabels are defined prior to this
root = tk.Tk(className = ' Function Grapher')
app = FunctionInput(root, win, axisLabels)
root.rowconfigure(0, weight = 1)
root.columnconfigure(0, weight = 1)
root.mainloop() # there is a button to exit the mainloop in my GUI
print app.getInput()
if __name__ == '__main__': main()
Also, as #A. Rodas said, to get rid of the grayness, I did:
self.typeFrame = tk.Frame(self.frame)
self.typeChoice = tk.StringVar(self.typeFrame)
self.typeChoice.set(None)