How to display string variables in Tkinter? - python

I am trying to create a GUI program in python to generate random Lottery numbers. I want to have a menu bar for choosing Powerball or MegaMillion. And after choosing it, there will be buttons to let user select how many tickets to show. But I cannot make the method work. I want to show different lines of number lists when I click the button, but it does show anything. I'm not finished yet since it doesn't work. I am new to Python and programming, please help! Thank you !
from tkinter import *
import random
class lotteryNum:
def __init__(self):
window=Tk()
window.title("Lottery Number Generator")
menubar = Menu(window)
window.config(menu=menubar)
self.pbLst = [x for x in range(1,70)]
self.pbLst2=[x for x in range(1,27)]
self.mmLst = [x for x in range(1,76)]
self.mmLst2=[x for x in range(1,16)]
self.usingLst=["*"]*6
#Type Menu
typeMenu = Menu(menubar, tearoff = 0)
menubar.add_cascade(label = "Which Lottery", menu = typeMenu)
typeMenu.add_command(label="Powerball", command= self.powerBall)
typeMenu.add_command(label="Mega Milion", command= self.megaMillion)
#Exit menu
exitmenu = Menu(menubar, tearoff = 0)
menubar.add_cascade(label = "Exit", menu = exitmenu)
exitmenu.add_command(label = "Quit", command = window.quit)
#Welcome label
Label(window, text="Welcome to Lottery Generator!").pack()
frame=Frame(window)
frame.pack()
#Text Label
self.showResults = StringVar()
Label(frame, text=self.showResults).pack()
Button(window, text="$2", command=self.runLottery()).pack(side=LEFT)
window.mainloop()
def powerBall(self):
# random.shuffle(self.pbLst)
# random.shuffle(self.pbLst2)
self.usingLst=self.pbLst
self.usingLst2=self.pbLst2
def megaMillion(self):
# random.shuffle(self.mmLst)
# random.shuffle(self.mmLst2)
self.usingLst=self.mmLst
self.usingLst2=self.mmLst2
def runLottery(self):
random.shuffle(self.usingLst)
random.shuffle(self.usingLst2)
self.usingLst[:5].extend(self.usingLst2[0])
self.showResults.set(self.usingLst)
lotteryNum()

I think your code should work if you change this line:
Label(frame, text=self.showResults).pack()
to this:
Label(frame, textvariable=self.showResults).pack()

Finished code just let whoever interested know what I'm try to do here.
from tkinter import *
import random
class lotteryNum:
def __init__(self):
window=Tk()
window.title("Lottery Number Generator")
menubar = Menu(window)
window.config(menu=menubar)
self.pbLst = [x for x in range(1,70)]
self.pbLst2=[x for x in range(1,27)]
self.mmLst = [x for x in range(1,76)]
self.mmLst2=[x for x in range(1,16)]
self.usingLst=[0]*6
self.usingLst2=[0]*6
#Type Menu
typeMenu = Menu(menubar, tearoff = 0)
menubar.add_cascade(label = "Which Lottery", menu = typeMenu)
typeMenu.add_command(label="Powerball", command= self.powerBall)
typeMenu.add_command(label="Mega Milion", command= self.megaMillion)
#Exit menu
exitmenu = Menu(menubar, tearoff = 0)
menubar.add_cascade(label = "Exit", menu = exitmenu)
exitmenu.add_command(label = "Quit", command = window.quit)
#Welcome label
Label(window, text="Welcome to Lottery Generator!").pack()
frame=Frame(window)
frame.pack()
#Text Label to show numbers
self.showResults = StringVar()
self.showResults5=StringVar()
oneTicket=Label(frame, textvariable=self.showResults).pack()
fiveTicket=Message(frame,textvariable=self.showResults5).pack()
#Buttons to generate tickets
Button(window, text="one ticket", command=self.showTicket).pack(side=LEFT)
Button(window, text="five tickets", command=self.showTicket5).pack(side=LEFT)
#Button to draw the tickets
Button(window, text="Draw tickets", command=self.drawTickets).pack()
#The process to draw each ticket
self.covered=False
window.mainloop()
def powerBall(self):
self.usingLst=self.pbLst
self.usingLst2=self.pbLst2
self.runLottery()
self.winingNumbers = self.showLst
def megaMillion(self):
self.usingLst=self.mmLst
self.usingLst2=self.mmLst2
self.runLottery()
self.winingNumbers = self.showLst
def runLottery(self):
random.shuffle(self.usingLst)
random.shuffle(self.usingLst2)
self.showLst=self.usingLst[:5]
self.showLst.sort()
self.showLst.append(self.usingLst2[0])
def showTicket(self):
self.runLottery()
if (self.showLst==self.winingNumbers):
self.covered = True
self.carry1=""
for i in range(6):
self.carry1+=str(self.showLst[i])+" "
self.showResults.set(self.carry1)
def showTicket5(self):
self.showTicket()
self.carry5=""
for i in range(4):
self.runLottery()
if(self.showLst==self.winingNumbers):
self.covered=True
for k in range(6):
self.carry5+=str(self.showLst[k])+" "
self.carry5+="\n"
self.showResults5.set(self.carry5)
def drawTickets(self):
top=Toplevel()
top.title("Draw Result")
label1=Label(top, text="The wining numbers are ").pack()
var1=StringVar()
label2 = Label(top, textvariable=var1).pack()
var1.set(self.winingNumbers)
var2=StringVar()
Label3 = Label(top, textvariable=var2).pack()
if (self.covered==True):
var2.set("You Win!!")
else:
var2.set("You Lose!!")
lotteryNum()

Print self.usingLst to make sure it contains something, and
self.showResults=Label(frame, text="no choices made")
self.showResults.pack()
then in runLottery
self.showResults["text"]="\n".join(self.usingLst)

Related

Modules and classes in Python for a desktop application

This is to be a desktop application for opening multiple small databases and running queries on them. So far I've written some code for opening forms as necessary. Is this a good way to do it? Also - the code shown opens two copies of each form - what am I doing wrong? It's my first attempt at Python and I'm a rudimentary programmer so simple answers would be of most help please. TIA (Python 3.9.6)
link_1.py
from tkinter import Tk
import link_2
root = Tk()
class ClassLink_1:
#if another function in the class is called, the __init__ function is run at start up
def __init__(self):
print("in link_1 __init__ instruction")
#the call_function function can be called at start up, or not, and will act accordingly
def call_function(self):
print("in call_function")
#the line below is run at start up whether or not another function in the class is called
print("in link_1")
root.withdraw() #hides the blank form at start up
#if __name__ == "__main__":
#the line below shows the link_2 form, whether or not the if __name__==__main__ condition is used as its condition
link_2.ClassLink_2(root).__init__(root)
#link_3.ClassLink_3(root).__init__(root)
#the line below runs call_function on start up to print text
ClassLink_1().call_function()
root.mainloop()
link_2.py
from tkinter import Tk, Button
from tkinter import * #for Toplevel
import link_3
root = Tk()
class ClassLink_2:
def __init__(self, master):
self.openNewWindow()
def openNewWindow(self):
newWindow = Toplevel(root) #creates a top level widget with the parent root (first parameter)
newWindow.title("Title opened from link_1")
newWindow.geometry("500x500")
label = Label(newWindow, text ="Opened from link_1").grid(row=1, column=1)
self.add_button = Button(newWindow, text="in ClassLink_2", command= self.do_add)
self.add_button.grid(row=3, column=1)
def do_add(self):
print("button pressed")
link_3.ClassLink_3(root).__init__(root)
root.withdraw() #hides the blank form at start up
link_3.py
from tkinter import Tk, Button
from tkinter import * #for Toplevel
root = Tk()
class ClassLink_3:
def __init__(self, master):
self.openNewWindow()
def openNewWindow(self):
newWindow = Toplevel(root) #creates a top level widget with the parent root (first parameter)
newWindow.title("Title opened from link_2")
newWindow.geometry("500x500")
label = Label(newWindow, text ="Opened from link_2").grid(row=1, column=1)
self.add_button = Button(newWindow, text="in ClassLink_3", command= self.do_add)
self.add_button.grid(row=3, column=1)
def do_add(self):
print("button pressed")
# link_4.ClassLink_4(root).__init__(root) this file has not yet been made
root.withdraw() #hides the blank form at start up
This is a proposed solution, can be expanded as needed. Constructive suggestions for improvement of the structure or code would be appreciated. TIA. I've left in the details in case they are of use to anyone.
link_1
from tkinter import Tk
import link_2
root = Tk()
class ClassLink_1:
def __init__(self):
print("in link_1 __init__ instruction")
root.withdraw() #hides the blank form at start up
link_2.ClassLink_2(root).openNewWindow(0)
root.mainloop()
link_2
from tkinter import Tk, Button
from tkinter import *
import link_3
root = Tk()
class ClassLink_2:
root.withdraw() #hides the blank form at start up
class_var_1 = 0
inst_var_1 = 0
def __init__(self, incoming_inst_var_1):
pass
def openNewWindow(self, inst_var_1_to_open):
newWindow = Toplevel(root)
newWindow.title("Title opened from link_1")
newWindow.geometry("500x500")
label = Label(newWindow, text ="Opened from link_1").grid(row=1, column=1)
self.add_button = Button(newWindow, text="in ClassLink_2", command= self.do_add)
self.add_button.grid(row=3, column=1)
self.add_button = Button(newWindow, text="increment class_var_1", command= self.inc_class_var_1)
self.add_button.grid(row=5, column=1)
self.inst_var_1 = inst_var_1_to_open
def do_add(self):
print("button pressed")
link_3.ClassLink_3(root).openNewWindow(0)
def inc_class_var_1(self):
ClassLink_2.class_var_1 += 2
self.inst_var_1 += 1
print("self.class_var_1 = " + (str)(self.class_var_1))
print("self.inst_var_1 = " + (str)(self.inst_var_1))
link_3
from tkinter import Tk, Button
from tkinter import *
from tkinter.ttk import Combobox
import tkinter.scrolledtext as tkscrolled
# import link_4 <filename of next form>
root = Tk()
class ClassLink_3:
class_var_1 = 0
inst_var_1 = 0
# ------------------------------- START CLASS CONTROLS -----------------------------
root.withdraw()
def __init__(self, incoming_inst_var_1):
pass
def openNewWindow(self, inst_var_1_to_open):
new_window = Toplevel(root)
self.widget_factory(new_window)
self.inst_var_1 = inst_var_1_to_open
def do_add(self):
print("button pressed")
# link_4.ClassLink_4(root).openNewWindow(0) # <filename of next form>
# ---------------------------------- END CLASS CONTROLS -----------------------------
# -------------------------------------- START CALCS --------------------------------------
def inc_class_var_1(self):
ClassLink_3.class_var_1 += 2
self.inst_var_1 += 1
print("self.class_var_1 = " + (str)(self.class_var_1))
print("self.inst_var_1 = " + (str)(self.inst_var_1))
# ---------------------------------------- END CALCS --------------------------------------
# ---------------------------------------- START FACTORY SHOPS-----------------------------------------
def widget_factory(self, new_window):
self.shop_window(new_window)
self.shop_labels(new_window)
self.shop_buttons(new_window)
self.shop_menu(new_window)
self.shop_listbox(new_window)
self.shop_combobox(new_window)
self.shop_radiobuttons(new_window)
self.shop_checkbuttons(new_window)
self.shop_entries(new_window)
self.shop_canvas(new_window)
self.shop_scale(new_window)
self.shop_scrollbars(new_window)
self.shop_textbox(new_window)
self.shop_menu(new_window)
pass
# ------------------------
def shop_window(self, new_window):
new_window.title("Title opened from link_2")
new_window.geometry("800x900")
def shop_labels(self, new_window):
self.label_1 = Label(new_window, text ="Opened from link_2").grid(row=1, column=1)
def shop_buttons(self, new_window):
self.button_1 = Button(new_window, text="in ClassLink_3", command= self.do_add)
self.button_1.grid(row=3, column=1)
self.button_2 = Button(new_window, text="increment class_var_1", command= self.inc_class_var_1)
self.button_2.grid(row=5, column=1)
def shop_listbox(self, new_window):
data=("one", "two", "three", "four")
self.listbox_1 = Listbox(new_window, height=5, selectmode='multiple')
for num in data:
self.listbox_1.insert(END,num)
self.listbox_1.grid(row=7, column=1)
def shop_combobox(self, new_window):
data=("one", "two", "three", "four")
self.combobox_1 = Combobox(new_window, values=data)
self.combobox_1.grid(row=8, column=3)
def shop_radiobuttons(self, new_window):
var_1 = IntVar()
var_1.set(1)
self.rad_btn_1 = Radiobutton(new_window, text="male", variable=var_1, value=1)
self.rad_btn_2 = Radiobutton(new_window, text="female", variable=var_1, value=2)
self.rad_btn_1.grid(row=9, column=1)
self.rad_btn_2.grid(row=9, column=2)
def shop_checkbuttons(self, new_window):
var_1 = IntVar()
var_2 = IntVar()
self.checkbtn_1 = Checkbutton(new_window, text = "Cricket", variable = var_1)
self.checkbtn_2 = Checkbutton(new_window, text = "Tennis", variable = var_2)
self.checkbtn_1.grid(row=10, column=1)
self.checkbtn_2.grid(row=10, column=2)
def shop_entries(self, new_window):
self.entry_1 = Entry(new_window, width = 20)
self.entry_1.insert(0,'Username')
self.entry_1.grid(row= 11, column=2)
self.entry_2 = Entry(new_window, width = 15)
self.entry_2.insert(0,'password')
self.entry_2.grid(row= 12, column=2)
#might want to place on a frame, see example https://coderslegacy.com/python/list-of-tkinter-widgets/
def shop_canvas(self, new_window):
canvas = Canvas(new_window, bg= 'white', width = 260,height = 260) #this is the background for the figure
# left and top of figure is from [x from left, y from top] of canvas right and bottom of figure from [x from left, y from top] of canvas
coordinates = 20, 50, 210, 230
arc = canvas.create_arc(coordinates, start=0, extent=250, fill="blue") #start is from E, extent is in degrees CCW
arc = canvas.create_arc(coordinates, start=250, extent=50, fill="red")
arc = canvas.create_arc(coordinates, start=300, extent=60, fill="yellow")
canvas.grid(row=2, column=1)
def shop_scale(self, new_window):
self.scale_1 = Scale(new_window, from_=0, to=10, orient=VERTICAL)
self.scale_1.grid(row=15, column=2)
self.scale_2 = Scale(new_window, from_=0, to=10, orient = HORIZONTAL)
self.scale_2.grid(row=15, column=3)
def shop_scrollbars(self, new_window):
self.scroll_vert = Scrollbar(new_window)
self.scroll_vert.grid(row=19, column=3)
self.listbox_3 = Listbox(new_window, yscrollcommand = self.scroll_vert.set )
for line in range(1, 100):
self.listbox_3.insert(END, "Number " + str(line))
self.listbox_3.grid(row=19 , column=2)
self.scroll_vert.config(command = self.listbox_3.yview)
def shop_textbox(self, new_window):
#make a frame with parent new_window
self.frame_textbox_1 = Frame(new_window)
self.frame_textbox_1.grid(row=1, column=5)
#make the textbox with parent frame
self.textbox_1 = Text(self.frame_textbox_1)
self.textbox_1.config(wrap=NONE, width=15, height=8) #width, height are characters x rows permitted wrap values should be WORD CHAR, or NONE
#make the X scrollbar with parent frame
self.scroll_text_horiz = Scrollbar(self.frame_textbox_1, orient="horizontal")
self.scroll_text_horiz.config(command = self.textbox_1.xview)
#make the Y scrollbar with parent frame
self.scroll_text_vert = Scrollbar(self.frame_textbox_1, orient="vertical")
self.scroll_text_vert.config(command = self.textbox_1.yview)
#pack the scrollbars before the texbox to allow them to fill the frame width and height
self.scroll_text_horiz.pack(side=BOTTOM, fill=X)
self.scroll_text_vert.pack(side=RIGHT, fill=Y)
self.textbox_1.pack(fill="y")
#connect the scrollbars to the textbox
self.textbox_1["xscrollcommand"] = self.scroll_text_horiz.set
self.textbox_1["yscrollcommand"] = self.scroll_text_vert.set
message = "the quick brown fox"
self.textbox_1.insert(1.1, message)
# ----------------------------------------------
def shop_menu(self, new_window):
print("in shop menu1")
menubar = Menu(new_window)
print("in shop_menu2")
file = Menu(menubar, tearoff=0)
file.add_command(label="New")
file.add_command(label="Open")
file.add_command(label="Save")
file.add_command(label="Save as...")
file.add_command(label="Close")
file.add_separator()
file.add_command(label="Exit", command=new_window.quit)
menubar.add_cascade(label="File", menu=file)
edit = Menu(menubar, tearoff=0)
edit.add_command(label="Undo")
edit.add_separator()
edit.add_command(label="Cut")
edit.add_command(label="Copy")
edit.add_command(label="Paste")
edit.add_command(label="Delete")
edit.add_command(label="Select All")
menubar.add_cascade(label="Edit", menu=edit)
help = Menu(menubar, tearoff=0)
help.add_command(label="About")
menubar.add_cascade(label="Help", menu=help)
new_window.config(menu=menubar)
print("in shop menu3")
# --------------------------------------- END FACTORY SHOPS---------------------------------------

How can I limit pick a question from a list only once in a random order?

I am trying to modify my flashcard python script. It works fine, but what I am triying to do is to modify the random function so that a single question (and its answer) it is not chosen twice. The script should not continue picking questions after the list is completed. I would also need to add a button that let me brwose back to previuos selections.
Any suggestions?
from tkinter import *
from tkinter import ttk
from random import randint
root = Tk()
root.title('Domande')
root.geometry("850x400")
root.resizable(True, True)
words = [
(("Stadio Olimpico"), ("ROMA")),
(("Stadio Artemio Franchi"), ("FIORENTINA")),
(("Stadio Armando Picchi"), ("LIVORNO")),
(("Stadio Luigi Ferraris"), ("SAMPDORIA"))
(("Stadio Arechi"), ("SALERNITANA"))
]
# get a count of our wods list
count = len(words)
def next():
global hinter, hint_count
#Clear screen
answer_label.config(text="")
label.config(text="")
hint_label.config(text="")
#Reset Hint stuff
hinter = ""
hint_count = 0
#Create random selection
global random_domande
random_domande = randint(0, count-1)
#Update label with Domande
domande.config(text=words[random_domande][0])
#Keep track of the hint
hinter = ""
hint_count = 0
def hint():
global hint_count
global hinter
if hint_count < len(words[random_domande][1]):
hinter = hinter + words[random_domande][1][hint_count]
hint_label.config(text=hinter)
hint_count +=1
#Define function to hide the widget
def hide_widget(widget):
widget.pack_forget()
widget.config(text=words[random_domande][1])
#Define a function to show the widget
def show_widget(widget):
widget.pack()
widget.config(text=words[random_domande][1])
#Labels
domande = Label(root, text="", font=("Times", 14))
domande.pack(side=TOP)
#Create an Label Widget
label = Label(root, text="", font=("Times", 14))
label.pack()
#Create Buttons
button_frame = Frame(root)
button_frame.pack()
hint_button = Button(button_frame, text="Hint", command=hint)
hint_button.pack()
button_show = Button(root, text= "Show", command= lambda:show_widget(label))
button_show.pack()
#Create a button Widget
button_hide = Button(root, text= "Hide", command=lambda:hide_widget(label))
button_hide.pack()
next_button = Button(button_frame, text="Next", command=next)
next_button.pack()
#Create Hint Label
hint_label = Label(root, text="")
hint_label.pack()
answer_label = Label(root, text="", font=("Times", 14))
answer_label.pack(side=BOTTOM)
#Run next function when the program starts
next()
root.mainloop()

Ending a Functions Tkinter window from another Function

from tkinter import *
root = Tk()
root.title("Tournament")
root.geometry("360x100")
def Choice():
second = Toplevel()
second.title("Tournament")
second.geometry("360x100")
command = root.withdraw()
typechoice = Label(second, text = "Are you part of a Team or Solo?")
typechoice.grid(row=0,column=0)
solo1 = Button(second, text = "Solo", command = Soloscreen)
solo1.grid(row=1,column=0)
team1 = Button(second, text = "Team", command = Teamscreen)
team1.grid(row=2,column=0)
def Soloscreen():
third = Toplevel()
third.title("Tournament")
third.geometry("360x100")
typechoice = Label(third, text="Enter your name")
typechoice.grid(row=0, column=0)
done = Button(third, text="Done")
done.grid(row=1, column=0)
def Teamscreen():
fourth = Toplevel()
fourth.title("Tournament")
fourth.geometry("360x100")
typechoice = Label(fourth, text="Enter your name")
typechoice.grid(row=0, column=0)
done = Button(fourth, text="Done")
done.grid(row=1, column=0)
# Creating GUI widgets
Start = Button(root, text="Start",width = "30", command=Choice, fg="red")
PHS = Button(root, text="Previous High Scores", width = "30", fg="red")
ENQ = Button(root, text="Enter New Questions", width = "30", fg="red")
# Displaying them on screen
Start.grid(row = 1, column = 3)
PHS.grid(row = 2, column = 3)
ENQ.grid(row = 3, column = 3)
root.mainloop()
As you can see here I have a pretty simple multiple window set up currently, what I dont understand is that I'm able to close the Root window with command = root.withdraw()however under the Soloscreen and Teamscreen windows the same command but changed to close the Choice screen wont seem to work?

how to display text after a button is pressed in python Tkinter

I am trying to display some text after a button is pressed but all I seem to be able to do make it so that text is displayed before the button is pressed or not at all.
here is my code so far:
import tkinter
def label1():
label2 = tkinter.Label(window1, text = "correct")
label.pack()
def Window2():
window1 = tkinter.Tk()
window1.title("start")
label = tkinter.Label(window1, text= "how do you spell this Sh--ld")
label.pack()
points = 0
i = points + 1
button = tkinter.Button(window1, text = "ou", command = label1)
button.pack()
window = tkinter.Tk()
window.title("menu")
button = tkinter.Button(window, text = "start", command = Window2)
button.pack()
I am trying to get the button in the Window2 subroutine to display the text
Here is how you can do it
import tkinter
def label1(root):
label = tkinter.Label(root, text = "correct")
label.pack()
def Window2():
window1 = tkinter.Tk()
window1.title("start")
label = tkinter.Label(window1, text= "how do you spell this Sh--ld")
label.pack()
points = 0
i = points + 1
button = tkinter.Button(window1, text = "ou", command = lambda root = window1: label1(root))
button.pack()
window = tkinter.Tk()
window.title("menu")
button = tkinter.Button(window, text = "start", command = Window2)
button.pack()
window.mainloop()

Creating new entry boxes with button Tkinter

How do i make the button to add two box (side by side) below when it is being clicked as the user decided to put more input?
def addBox():
labelframe = Tkinter.Frame()
labelframe.bind("<Add Input>", callback)
labelframe.pack()
labelframe = Tkinter.Frame()
labelFrom = Tkinter.Label(labelframe, text= "from")
labelFrom.grid(column=1, row=0)
e = Tkinter.Entry(labelframe)
e.grid(column=1, row=1)
labelTo = Tkinter.Label(labelframe, text= "to")
labelTo.grid(column=2, row=0)
e2 = Tkinter.Entry(labelframe)
e2.grid(column=2, row=1)
labelframe.pack()
addboxButton = Button( root,text='<Add Time Input>', fg="Red",command="addBox")
addboxButton.pack(side=Tkinter.TOP)
This is example how to add Entry.
Probably you get problem because you use quotation marks in command=addBox
Because you will have to get values from entries you have to remeber them on list.
I add button which print text from entries.
from Tkinter import *
#------------------------------------
def addBox():
print "ADD"
ent = Entry(root)
ent.pack()
all_entries.append( ent )
#------------------------------------
def showEntries():
for number, ent in enumerate(all_entries):
print number, ent.get()
#------------------------------------
all_entries = []
root = Tk()
showButton = Button(root, text='Show all text', command=showEntries)
showButton.pack()
addboxButton = Button(root, text='<Add Time Input>', fg="Red", command=addBox)
addboxButton.pack()
root.mainloop()
#------------------------------------
EDIT:
Example with boxes side by side.
I use new frame to keep entries side by side using grid().
This way I don't mix grid() with pack() in main window/frame.
I use len(all_entries) to get number of next free column.
from Tkinter import *
#------------------------------------
def addBox():
print "ADD"
# I use len(all_entries) to get nuber of next free column
next_column = len(all_entries)
# add label in first row
lab = Label(frame_for_boxes, text=str(next_column+1))
lab.grid(row=0, column=next_column)
# add entry in second row
ent = Entry(frame_for_boxes)
ent.grid(row=1, column=next_column)
all_entries.append( ent )
#------------------------------------
def showEntries():
for number, ent in enumerate(all_entries):
print number, ent.get()
#------------------------------------
all_entries = []
root = Tk()
showButton = Button(root, text='Show all text', command=showEntries)
showButton.pack()
addboxButton = Button(root, text='<Add Time Input>', fg="Red", command=addBox)
addboxButton.pack()
frame_for_boxes = Frame(root)
frame_for_boxes.pack()
root.mainloop()
#------------------------------------
EDIT:
Another example:
from Tkinter import *
#------------------------------------
def addBox():
print "ADD"
frame = Frame(root)
frame.pack()
Label(frame, text='From').grid(row=0, column=0)
ent1 = Entry(frame)
ent1.grid(row=1, column=0)
Label(frame, text='To').grid(row=0, column=1)
ent2 = Entry(frame)
ent2.grid(row=1, column=1)
all_entries.append( (ent1, ent2) )
#------------------------------------
def showEntries():
for number, (ent1, ent2) in enumerate(all_entries):
print number, ent1.get(), ent2.get()
#------------------------------------
all_entries = []
root = Tk()
showButton = Button(root, text='Show all text', command=showEntries)
showButton.pack()
addboxButton = Button(root, text='<Add Time Input>', fg="Red", command=addBox)
addboxButton.pack()
root.mainloop()
#------------------------------------
First of all, the indentation is a whole mess, so I don't know where does the addBox function end ..
Second, I don't think you need a button, I suppose a checkbutton will do the same thing and it's also more common and familiar to users, I once had this problem and I simply created an entry box and put above it a label indicating that it's optional, and as for code, I simply ignored it if it was empty and verified the input if I found any input ..Howerver, that was for only one entry box, and you probably will need something more complex ..
See this ..
class OptionsView(Frame):
"""Frame for options in main window"""
def __init__(self, x, y, parent):
Frame.__init__(self, parent)
self.x = x
self.y = y
self.placed = False
self.hidden = False
self.btn = Button(self, text = 'Button attached to the frame ..', command = lambda: print('Button in frame clicked ..')).pack()
def pack(self):
self.place(x = self.x, y = self.y)
self.placed = True
def toggle_view(self):
if self.hidden:
self.pack()
self.hidden = False
else:
self.place_forget()
self.hidden = True
if __name__ == '__main__':
def m_frame():
if val.get() and not options_frame.placed:
print('Showing Frame ..')
options_frame.pack()
else:
print('Toggling Frame ..')
options_frame.toggle_view()
root = Tk()
root.geometry('300x400+500+600')
root.title('Testing Hiding Frames ..')
options_frame = OptionsView(200, 300, root)
val = BooleanVar(value = False)
Checkbutton(text = 'View more Options ..', var = val, command = m_frame).place(x=root.winfo_height()/2, y=root.winfo_width()/2)
try: root.mainloop()
except e: showerror('Error!', 'It seems there\'s a problem ..', str(e))
Ofcourse you can also modify the length and the x axis of the main window if you want to be more realistic ..

Categories

Resources