tkinter root.destroy() without killing the whole window - python

I am recreating the game Wordle for practice.
I am trying to find a function that allows me to destroy all widgets in my tkinter window.
root.destroy() isn't a solution because it just closes the whole window.
I want to use this function to, whenever we win the game, restart the whole program without having to manually do it.
Program:
from tkinter import *
from tkinter import ttk
import tkinter as tk
from english_words import english_words_alpha_set
import time
guess = "bored"
guess = guess.upper()
word=""
a=0
def callback1(var, index, mode):
root.entry2.configure(state="normal")
root.entry2.focus()
root.entry1.configure(state="disabled")
root.hasfocus = "entry2"
def callback2(var, index, mode):
root.entry3.configure(state="normal")
root.entry3.focus()
root.entry2.configure(state="disabled")
root.hasfocus = "entry3"
def callback3(var, index, mode):
root.entry4.configure(state="normal")
root.entry4.focus()
root.entry3.configure(state="disabled")
root.hasfocus = "entry4"
def callback4(var, index, mode):
root.entry5.configure(state="normal")
root.entry5.focus()
root.entry4.configure(state="disabled")
root.hasfocus = "entry5"
def callback5(var, index, mode):
root.entry5.configure(state="disabled")
root.hasfocus = "none"
def newRow():
boxes = [root.box1, root.box2, root.box3, root.box4, root.box5]
word = root.name1.get() + root.name2.get() + root.name3.get() + root.name4.get() + root.name5.get()
word=word.upper()
root.greenBoxes=0
def checkBg():
if word[a] == guess[a]:
root.greenBoxes=root.greenBoxes+1
print("greenBoxes=", root.greenBoxes)
return '#538D4E'
elif word[a] in guess:
return '#B59F3B'
else:
return '#3A3A3C'
root.entry1.destroy()
root.entry2.destroy()
root.entry3.destroy()
root.entry4.destroy()
root.entry5.destroy()
a=0
while a < 5:
boxes[a].configure(text=word[a], bg=checkBg(), fg = "white")
a=a+1
if root.greenBoxes == 5: #if player won:
root.WinMsg = Label(root, height=2, width=28, bg='#2d2d2f', fg='white', text='You\'ve won! The word was \"' + guess[0] + guess[1:5].lower() +"\"", font="Calibri 20")
root.WinMsg.place(x=65, y=100) #say that he won
#*destroy all widgets*
root.CreateWindow() #remake all widgets (to start a new game)
return
root.rows = root.rows+1
if root.rows < 6: #if player still have any try
root.d=root.d+70
root.createBoxes()
root.createEntry()
else: #if player lost
root.GameOverMsg = Label(root, height=2, width=28, bg='#2d2d2f', fg='white', text='You\'ve lost! The word was \"' + guess[0] + guess[1:5].lower() +"\"", font="Calibri 20")
root.GameOverMsg.place(x=65, y=100) #says that he lost
#*destroy all widgets*
root.CreateWindow() #remake all widgets (to start a new game)
return
class root(Tk):
def __init__(self):
super(root, self).__init__()
self.title("Wordle")
self.minsize(580,465)
self.windowBG = '#121213'
self.CreateWindow()
def CreateWindow(self):
self.configure(bg=self.windowBG)
self.hasfocus = ""
self.d=0
self.rows=0
self.greenBoxes = 0
self.createBoxes()
self.createEntry()
self.backspace = Button(self, text="Backspace", width=8, font ="Calibri 18", command=self.do_backspace)
self.backspace.place(x=465, y=62)
self.enter = Button(self, text="Enter", width=6, font ="Calibri 18", command=self.do_enter)
self.enter.place(x=480, y=125)
def createBoxes(self):
self.box1 = tk.Label(self, text="", font="Calibri", height=2, width=6, bg="#3A3A3C")
self.box1.place(x=70, y=30+self.d)
self.box2 = tk.Label(self, text="", font="Calibri", height=2, width=6, bg="#3A3A3C")
self.box2.place(x=150, y=30+self.d)
self.box3 = tk.Label(self, text="", font="Calibri", height=2, width=6, bg="#3A3A3C")
self.box3.place(x=230, y=30+self.d)
self.box4 = tk.Label(self, text="", font="Calibri", height=2, width=6, bg="#3A3A3C")
self.box4.place(x=310, y=30+self.d)
self.box5 = tk.Label(self, text="", font="Calibri", height=2, width=6, bg="#3A3A3C")
self.box5.place(x=390, y=30+self.d)
def do_backspace(self):
if self.hasfocus == "entry1":
pass
elif self.hasfocus == "entry2":
self.entry1.configure(state="normal")
self.entry1.delete(0, 'end')
self.entry1.configure(state="normal")
self.entry1.focus()
self.hasfocus="entry1"
self.entry2.configure(state="disabled")
elif self.hasfocus == "entry3":
self.entry2.configure(state="normal")
self.entry2.delete(0, 'end')
self.entry2.configure(state="normal")
self.entry2.focus()
self.hasfocus="entry2"
self.entry3.configure(state="disabled")
elif self.hasfocus == "entry4":
self.entry3.configure(state="normal")
self.entry3.delete(0, 'end')
self.entry3.configure(state="normal")
self.entry3.focus()
self.hasfocus="entry3"
self.entry4.configure(state="disabled")
elif self.hasfocus == "entry5":
self.entry4.configure(state="normal")
self.entry4.delete(0, 'end')
self.entry4.configure(state="normal")
self.entry4.focus()
self.hasfocus="entry4"
self.entry5.configure(state="disabled")
else:
self.entry5.configure(state="normal")
self.entry5.delete(0, 'end')
self.entry5.configure(state="normal")
self.entry5.focus()
self.hasfocus="entry5"
def do_enter(self):
if len(self.name1.get() + self.name2.get() + self.name3.get() + self.name4.get() + self.name5.get()) == 5:
newRow()
else:
self.FiveLetterWord = Label(self, height=2, width=22, bg='#2d2d2f', fg='white', text='Word must be of 5 letters', font="Calibri 20", background=self.windowBG,highlightbackground='#3A3A3C', highlightthickness=2)
self.FiveLetterWord.place(x=100, y=100)
self.update_idletasks()
self.after(3000)
self.FiveLetterWord.destroy()
def createEntry(self):
self.name1 = StringVar()
self.entry1 = ttk.Entry(self, width=2, textvariable = self.name1, font="Calibri 15", justify='center')
self.entry1.place(x=90, y=40+self.d)
self.name2 = StringVar()
self.entry2 = ttk.Entry(self, width=2, textvariable = self.name2, font="Calibri 15", justify='center')
self.entry2.place(x=170, y=40+self.d)
self.entry2.configure(state="disabled")
self.name3 = StringVar()
self.entry3 = ttk.Entry(self, width=2, textvariable = self.name3, font="Calibri 15", justify='center')
self.entry3.place(x=250, y=40+self.d)
self.entry3.configure(state="disabled")
self.name4 = StringVar()
self.entry4 = ttk.Entry(self, width=2, textvariable = self.name4, font="Calibri 15", justify='center')
self.entry4.place(x=330, y=40+self.d)
self.entry4.configure(state="disabled")
self.name5 = StringVar()
self.entry5 = ttk.Entry(self, width=2, textvariable = self.name5, font="Calibri 15", justify='center')
self.entry5.place(x=410, y=40+self.d)
self.entry5.configure(state="disabled")
self.entry1.focus() ; hasfocus = "entry1"
self.name1.trace_add("write", callback1)
self.name2.trace_add("write", callback2)
self.name3.trace_add("write", callback3)
self.name4.trace_add("write", callback4)
self.name5.trace_add("write", callback5)
root=root()
root.mainloop()

You can use winfo_children to get a list of all child widgets of the root window, and then you can iterate over the list to destroy each child.
for child in root.winfo_children():
child.destroy()
From that point on, you have a root window with nothing in it.

Related

Trying to save values from tkInter scale

This is my first post so please have patience
I've got a school assignment to create an art supplies application and I've drawn a blank why my tkinter scale values are not saving to a file.
The customer details and submit button code works as expected (saves to a file = info.txt)
The Order tab page doesn't work as expected = does not append info.txt with specific quantities of art supplies ordered
Here's my code
#def mainmenu():
from tkinter import *
from tkinter import ttk
import re
NON_ALPHA_RE = re.compile('[^A-Z0-9]+')
POSTCODE_RE = re.compile('^[A-Z]{1,2}[0-9]{1,2}[A-Z]? [0-9][A-Z]{2}$')
def normalise_postcode(eZIP_Postalcode):
eZIP_Postalcode = NON_ALPHA_RE.sub('', eZIP_Postalcode.upper())
eZIP_Postalcode = eZIP_Postalcode[:-3] + ' ' + eZIP_Postalcode[-3:]
if POSTCODE_RE.match(eZIP_Postalcode):
return eZIP_Postalcode
return None
def submit() :
invalidtext_1.set("")
invalidtext_2.set("")
invalidtext_3.set("")
invalidtext_4.set("")
invalidtext_5.set("")
eName =Name.get()
eSurname =Surname.get()
ecountry =country.get()
ecity =city.get()
eAddressLine1 = AddressLine1.get()
eAddressLine2 = AddressLine2.get()
eState_Province_Region = State_Province_Region.get()
eZIP_Postalcode = ZIP_Postalcode.get()
valid = True
if eName.isalpha() == False:
invalidtext_1.set("Invalid forename. Please use letters only.")
valid = False
if eSurname.isalpha() == False:
invalidtext_2.set("Invalid surname. Please use letters only.")
valid = False
if ecountry.isalpha() == False:
invalidtext_3.set("Invalid country name. Please use letters only.")
valid = False
if ecity.isalpha() == False:
invalidtext_4.set("Invalid city name. Please use letters only.")
valid = False
if eZIP_Postalcode != normalise_postcode(eZIP_Postalcode):
invalidtext_5.set("Please enter a valid postcode.")
valid = False
if valid == False:
return
else:
eName = eName.ljust(150)
eSurname = eSurname.ljust(150)
ecountry = ecountry.ljust(150)
ecity = ecity.ljust(150)
eAddressLine1 = eAddressLine1.ljust(150)
eAddressLine2 = eAddressLine2.ljust(150)
eState_Province_Region = eState_Province_Region.ljust(150)
eZIP_Postalcode = eZIP_Postalcode.ljust(150)
fileObject = open("Info.txt","a")
fileObject.write(eName +"\n" + eSurname +"\n" + ecountry +"\n" + ecity +"\n" + eAddressLine1 +"\n" + eAddressLine2 +"\n" + eState_Province_Region +"\n" + eZIP_Postalcode +"\n")
fileObject.close()
return
def submitNumber():
Paint=Paint.get()
Paper=Paper.get()
PaintBrush =PaintBrush.get()
Easles=Easles.get()
Pencils=Pencils.get()
Paint = Paint.ljust(150)
Paper = Paper.ljust(150)
PaintBrush = PaintBrush.ljust(150)
Easles = Easles.ljust(150)
Pencils = Pencils.ljust(150)
fileObject = open("Info.txt","a")
fileObject.write(paint + paper + paintbrush + Easles + pencils +"\n")
fileObject.close()
def mainWindow():
global Name, invalidtext_1, frame1, invalidtext_2,Surname,city,country,invalidtext_3,invalidtext_4,AddressLine1,AddressLine2,State_Province_Region,ZIP_Postalcode,invalidtext_5
window=Tk()
window.title("Artist Products")
window.configure(background = "#800000")
window.resizable(width=True, height=True)
# DON'T NEED window.geometry("500x300") #Width x Height
tab_control = ttk.Notebook(window)
tab1 = ttk.Frame(tab_control)
#Tab 1 (as in the number 1!)
tab_control.add(tab1, text='Customer details')
Label (tab1, text="Name:" , bg="#800", fg="white", font="futuran 12").grid(row=1, column=0)
Name=StringVar()
eName=Entry(tab1, textvariable=Name)
eName.grid(row=1, column=1)
invalidtext_1=StringVar()
invalid_1= Label(tab1, textvariable=invalidtext_1, font="Helvetica 12 ", fg="red")
invalid_1.grid(row=1,column=2, sticky=W)
Label (tab1, text="Surname:" , bg="#800", fg="white", font="futuran 12").grid(row=2, column=0)
Surname=StringVar()
eSurname=Entry(tab1, textvariable=Surname)
eSurname.grid(row=2, column=1)
invalidtext_2=StringVar()
invalid_2= Label(tab1, textvariable=invalidtext_2, font="Helvetica 12 ", fg="red")
invalid_2.grid(row=2,column=2, sticky=W)
Label (tab1, text="Adress Line 1:" , bg="#800", fg="white", font="futuran 12").grid(row=3, column=0)
AddressLine1=StringVar()
eAddressLine1=Entry(tab1, textvariable=AddressLine1)
eAddressLine1.grid(row=3, column=1)
Label (tab1, text="Adress Line 2:" , bg="#800", fg="white", font="futuran 12").grid(row=4, column=0)
AddressLine2=StringVar()
eAddressLine2=Entry(tab1, textvariable=AddressLine2)
eAddressLine2.grid(row=4, column=1)
Label (tab1, text="State/province/region:" , bg="#800", fg="white", font="futuran 12").grid(row=5, column=0)
State_Province_Region=StringVar()
eState_Province_Region=Entry(tab1, textvariable=State_Province_Region)
eState_Province_Region.grid(row=5, column=1)
Label (tab1, text="ZIP/postal code:" , bg="#800", fg="white", font="futuran 12").grid(row=6, column=0)
ZIP_Postalcode=StringVar()
eZIP_Postalcode=Entry(tab1, textvariable=ZIP_Postalcode)
eZIP_Postalcode.grid(row=6, column=1)
invalidtext_5=StringVar()
invalid_5= Label(tab1, textvariable=invalidtext_5, font="Helvetica 12 ", fg="red")
invalid_5.grid(row=6,column=2, sticky=W)
Label (tab1, text="Country name:" , bg="#800", fg="white", font="futuran 12").grid(row=7, column=0)
country=StringVar()
ecountry=Entry(tab1, textvariable=country)
ecountry.grid(row=7, column=1)
invalidtext_3=StringVar()
invalid_3= Label(tab1, textvariable=invalidtext_3, font="Helvetica 12 ", fg="red")
invalid_3.grid(row=7,column=2, sticky=W)
Label (tab1, text="City:" , bg="#800", fg="white", font="futuran 12").grid(row=8, column=0)
city=StringVar()
ecity=Entry(tab1, textvariable=city)
ecity.grid(row=8, column=1)
invalidtext_4=StringVar()
invalid_4= Label(tab1, textvariable=invalidtext_4, font="Helvetica 12 ", fg="red")
invalid_4.grid(row=8,column=2, sticky=W)
####Tab 2
tab2 = ttk.Frame(tab_control)
tab_control.add(tab2, text='View All Products')
Label (tab2, text='Paper(50 pages non lined):£3',bg="#800", fg="white", font="futuran 12").grid(row=1, column=0)
Paper = Scale(tab2, from_=0, to=100, orient=HORIZONTAL)
Paper.grid(row=1, column=1)
Label (tab2, text='Paint (acrylic):£6' ,bg="#800", fg="white", font="futuran 12").grid(row=2, column=0)
Paint = Scale(tab2, from_=0, to=100, orient=HORIZONTAL)
Paint.grid(row=2, column=1)
Label (tab2, text='Paint brush:£4' ,bg="#800", fg="white", font="futuran 12").grid(row=3, column=0)
PaintBrush = Scale(tab2, from_=0, to=100, orient=HORIZONTAL)
PaintBrush.grid(row=3, column=1)
Label (tab2, text='Easels:£6' ,bg="#800", fg="white", font="futuran 12").grid(row=4, column=0)
Easels = Scale(tab2, from_=0, to=100, orient=HORIZONTAL)
Easels.grid(row=4, column=1)
Label (tab2, text='Pencils:£4.50' ,bg="#800", fg="white", font="futuran 12").grid(row=5, column=0)
Pencils = Scale(tab2, from_=0, to=100, orient=HORIZONTAL)
Pencils.grid(row=5, column=1)
#Tab 3
tab3 = ttk.Frame(tab_control)
tab_control.add(tab3, text='Invoices')
tab_control.grid(row=1, column=1)
#Tab 4
tab4 = ttk.Frame(tab_control)
tab_control.add(tab4, text='Basket')
tab_control.grid(row=1, column=1)
Label (tab4, text="Basket",bg="#800", fg="white", font="futuran 12").grid(row=1, column=0)
#Tab 5
tab5 = ttk.Frame(tab_control)
tab_control.add(tab5, text='Orders')
tab_control.grid(row=1, column=1)
#buttons
b6=Button(tab1, text="Close",command=quit, width=10)
b6.grid(row=12, column=0)
b6=Button(tab2, text="Close",command=quit, width=10)
b6.grid(row=12, column=0)
b6=Button(tab3, text="Close",command=quit, width=10)
b6.grid(row=12, column=0)
b6=Button(tab4, text="Close",command=quit, width=10)
b6.grid(row=12, column=0)
b6=Button(tab5, text="Close",command=quit, width=10)
b6.grid(row=12, column=0)
b18= Button(tab1, text=" Submit ",command=submit,width=10)
b18.grid(row=12, column=1)
b17= Button(tab2, text=" Submit ",command=submit,width=10)
b17.grid(row=12, column=1)
frame2 = Frame(window)
frame2.grid()
return window
window = mainWindow()
window.mainloop()
mainWindow()
I've also tried to get the customer details submit button to save to the file and then close down the customer details tab or ar least move the focus to the 'View all products' tab (so that the user can then concentrate on their order).
Help!
It looks like your problem is one of variable names. You are clobbering the scale object with the result of a call to get(), but then you write to what I assume was the variable you intended to assign. That variable is never initialized and is therefore None, so nothing is written to the file.
e.g.
Paint = Paint.get()
...
Paint = Paint.ljust(150)
...
fileObject.write(... + paint + ...)
should be
paint = Paint.get()
...
paint = Paint.ljust(150)
...
fileObject.write(... + paint)

How to deselect a radio button tkinter

I have looked at several online tutorials, none of them seem to work properly, I need to have the radio button deselected once the clear button is clicked. The .deselect() method does nothing. Clearing the text and entry boxes is working properly. Please assist.
Thank you,
from tkinter import *
class Example(Frame):
def __init__(self, parent):
Frame.__init__(self, parent, background="white")
self.parent = parent
self.parent.title("TCPDUMP Creator")
#self.centerWindow()
self.pack(fill=BOTH, expand=1)
menubar = Menu(self.parent)
self.parent.config(menu=menubar)
fileMenu = Menu(menubar)
fileMenu.add_command(label="Exit", command=self.quit)
menubar.add_cascade(label="File", menu=fileMenu)
self.columnconfigure(2, weight=5)
lf = LabelFrame(parent, text="Filter Data")
lf.pack(fill="both", expand="yes")
f = LabelFrame(lf, width=600, height=300)
frame1 = LabelFrame(lf, text="Interface")
frame1.pack(side="top", fill="both")
#frame1.place(relx=0.10, rely=0.125, anchor=NW)
int_lbl = Label(frame1, text="Int.")
int_lbl.pack(side="left", fill=X)
self.int_entry = Entry(frame1, width=15)
self.int_entry.pack(side="left")
frame2 = Label(lf, text="")
frame2.pack(side='top', fill=X)
self.anyInt = BooleanVar()
Checkbutton(frame1, text="Any", variable = self.anyInt).pack(side="left")
frame2=LabelFrame(lf, text="IP Options")
frame2.pack(side="top", fill="both")
self.notSrc = BooleanVar()
Checkbutton(frame2, text = "Not--", variable = self.notSrc).pack(side="left")
self.srcIP = BooleanVar()
Checkbutton(frame2, text="Src", variable = self.srcIP).pack(side="left")
self.src_entry = Entry(frame2, width=15)
self.src_entry.pack(side="left")
self.AndOr = StringVar()
self.AndOr.set(None)
andbtn = Radiobutton(frame2, text = "And", variable = self.AndOr, value = "And").pack(side="left", padx=25)
orbtn = Radiobutton(frame2, text = "Or", variable = self.AndOr, value = "Or").pack(side="left", padx=15)
self.notDst = BooleanVar()
Checkbutton(frame2, text = "Not--", variable = self.notDst).pack(side="left", padx=20)
self.dstIP = BooleanVar()
Checkbutton(frame2, text="Dst", variable = self.dstIP).pack(side="left")
self.dst_entry = Entry(frame2, width=15)
self.dst_entry.pack(side="left")
frame3 = Label(lf, text="")
frame3.pack(side='top', fill=X)
frame3 = LabelFrame(lf, text="")
frame3.pack(side="top", fill="both")
self.AndOrport = StringVar()
self.AndOrport.set(None)
srcAnd=Radiobutton(frame3, text = "And", variable = self.AndOrport, value = "And").pack(side='left')
self.srcOr=Radiobutton(frame3, text = "Or", variable = self.AndOrport, value = "Or").pack(side='left')
frame4 = Label(lf, text="")
frame4.pack(side='top', fill=X)
frame4 = LabelFrame(lf, text="Ports")
frame4.pack(side="top", fill="both")
self.notSrcPort = BooleanVar()
Checkbutton(frame4, text = "Not--", variable = self.notSrcPort).pack(side="left")
self.srcport_lbl = Label(frame4, text="Src Port")
self.srcport_lbl.pack(side="left")
self.srcport_entry = Entry(frame4, width=15)
self.srcport_entry.pack(side="left")
self.SrcDstport = StringVar()
self.SrcDstport.set(None)
Radiobutton(frame4, text = "And", variable = self.SrcDstport, value = "And").pack(side='left', padx=25)
Radiobutton(frame4, text = "Or", variable = self.SrcDstport, value = "Or").pack(side='left', padx=15)
self.notDstPort = BooleanVar()
Checkbutton(frame4, text = "Not--", variable = self.notDstPort).pack(side="left")
self.dstport_lbl = Label(frame4, text="Dst Port")
self.dstport_lbl.pack(side="left")
self.dstport_entry = Entry(frame4, width=15)
self.dstport_entry.pack(side="left")
frame5 = Label(lf, text="")
frame5.pack(side="top", fill=X)
frame5 = LabelFrame(lf, text="Options")
frame5.pack(side="top", fill="both")
self.listInterfaces = BooleanVar()
Checkbutton(frame5, text = "List Interfaces", variable = self.listInterfaces).pack(side="left")
cap_lbl = Label(frame5, text="# of Packets to Capture")
cap_lbl.pack(side="left")
self.cap_entry = Entry(frame5, width=3)
self.cap_entry.pack(side="left")
self.noDNS = BooleanVar()
Checkbutton(frame5, text = "Don't Translate Hostnames & Ports", variable = self.noDNS).pack(side="left", padx=15)
verbosity_lbl = Label(frame5, text="Verbosity:")
verbosity_lbl.pack(side="left")
self.verbosity = StringVar()
self.verbosity.set(None)
Radiobutton(frame5, text = "Low", variable = self.verbosity, value = "-v").pack(side='left')
Radiobutton(frame5, text = "Med", variable = self.verbosity, value = "-vv").pack(side='left', padx=15)
Radiobutton(frame5, text = "High", variable = self.verbosity, value = "-vvv").pack(side='left', padx=15)
frame6 = LabelFrame(lf, text="")
frame6.pack(side="top", fill="both")
self.timeformat = StringVar()
self.timeformat.set(None)
Radiobutton(frame6, text="Human Readable Time Format", variable=self.timeformat, value="-tttt").pack(side="left", padx=10)
self.write2file = StringVar()
self.write2file.set(None)
Radiobutton(frame6, text = "Write to File", variable = self.write2file, value="-w").pack(side='left')
write_lbl = Label(frame6, text="Filename")
write_lbl.pack(side="left")
self.file_entry = Entry(frame6, width=15)
self.file_entry.pack(side='left')
frame7 = Label(lf, text="")
frame7.pack(side='top', fill=X)
frame8 = Label(lf, text="")
frame8.pack(side="top", fill=X)
createBttn = Button(frame8, text="Create", width=15, height=2, relief="ridge", anchor=CENTER, command=self.create)
createBttn.pack(side="left", padx=70)
clearBttn = Button(frame8, text="Clear", width=15, height=2, relief="ridge", anchor=CENTER, command=self.clear)
clearBttn.pack(side="left", padx=70)
self.exitBttn = Button(frame8, text="Exit", width=15, height=2, relief="ridge", anchor=CENTER, command=self.exit)
self.exitBttn.pack(side="left", padx=70)
frame9 = Label(lf, text="Filter Data")
frame9.pack(side="top", fill=X)
frame10 = Label(lf, text="")
frame10.pack(side="left")
self.filterData = Text(frame10, width=95, height=1.2)
self.filterData.pack(side="left")
def centerWindow(self):
w = 600
h = 300
sw = self.parent.winfo_screenwidth()
sh = self.parent.winfo_screenheight()
x = (sw - w)/2
y = (sh - h)/2.7
self.parent.geometry("%dx%d+%d+%d" % (w, h, x, y))
def clear(self):
try:
self.filterData.delete(0.0, END) #delete from text box
self.int_entry.delete(0, END) #delete from entry box
self.src_entry.delete(0, END)
self.dst_entry.delete(0, END)
self.srcport_entry.delete(0, END)
self.dstport_entry.delete(0, END)
self.file_entry.delete(0, END)
self.cap_entry.delete(0, END)
self.anyInt.set(0)
self.notSrc.set(0)
self.srcIP.set(0)
self.noDNS.set(0)
self.listInterfaces.set(0)
self.notDstPort.set(0)
self.notSrcPort.set(0)
self.dstIP.set(0)
self.srcAnd.deselect()
self.srcOr.deselect()
self.SrcDstport.deselect()
deselect(self.timeformat)
self.write2file.deselect()
self.SrcDstport.deselect()
except:
pass
def exit(self):
self.quit()
def create(self):
if self.anyInt.get():
self.filterData.insert(0.0, "tcpdump " + "-i " + "any")
else:
self.filterData.insert(0.0, "tcpdump " + "-i " + self.int_entry.get())
def main():
root = Tk()
app = Example(root)
root.mainloop()
if __name__ == '__main__':
main()
self.SrcDstport.deselect()
You are trying to deselect the StringVar. You need to set it to something that isn't an option, in other words a value that none of the Radiobuttons use in the value argument:
self.SrcDstport.set(None)

Using StringVar data as a list

I've been following this website for a while. It is really helpful. So, thanks for all the useful tips.
I've been searching for this answer for the past two weeks without any success, so now I'm compelled to ask out of total frustration with my current obstacle.
How do you use StringVar as a list?
Basically, I was coding the following program for my wife. The code is pretty messy as it is my first program I've tried to code.
The idea was that I would take 3 variables; password, secret number and website and then do some work on them using if statements and lists to create a unique password.
First problem was that I couldn't restrict the character length of the entry widgets but in the end i solved that but i still want to limit the characters that can be input.
for instance in the website entry box, i want to allow only letters.
If I could convert StringVar to a list, I could do some work with messy if statements to allow only certain characters in each index but everythime i try it says that stringvars cant be used as a list.
I need them as a list to limit the type of characters that can be entered and also so that i can do work on the variables to get the final output.
CODE:
from Tkinter import *
import Tkinter
from PIL import Image, ImageTk
import os
Title= ("Helvetica", 20, "bold", "underline")
Heading= ("Courier", 20, "bold")
Body= ("Courier", 15)
Body1= ("Courier", 15, "bold")
notice= ("Courier", 10)
Body2= ("Courier", 15, "bold", "underline")
root = Tk()
root.title("Koala Series: Encrypter")
root.configure(background="#ffefd5")
root.geometry('{}x{}'.format(510, 600))
root.columnconfigure(0, weight=1)
root.rowconfigure(0, weight=1) # not needed, this is the default behavior
root.rowconfigure(1, weight=1)
root.rowconfigure(2, weight=1)
website = StringVar()
Titlemsg = Label(root, text="Koala Encrypter", font=Title, bg="#00FA9A", relief=RAISED,)
Titlemsg.grid( row=7, pady=25, sticky=N+S+E+W)
img1 = ImageTk.PhotoImage(Image.open("koala.jpeg"))
startpic = Label(root, image = img1, relief=RIDGE )
startpic.grid( row=10,pady=25, )
Head = Label(root,anchor=CENTER,text="Welcome to the Koala Encrypter \n\n A Koala series tool that allows you\n\n to Encrypt your passwords \n\n Click \'Start Encrypting\' to continue \n\n", font=Body, bg="#ffefd5", relief=RAISED,)
Head.grid( row=14, pady=25, columnspan=2, sticky=N+S+E+W)
web = Label(root, text="WEBSITE: ", font=Body, bg="#ffefd5", justify=CENTER,)
#website.set("Enter your website here")
entry = Entry(root,textvariable=website , justify=CENTER,relief=SUNKEN,cursor="pencil", takefocus=True )
Notice1 = Label( text="Please only insert the first 5 letters of the website!!",font=notice, bg="#ffefd5", fg="#0000ff",)
passw = Label(root, text="PASSWORD: ", font=Body, bg="#ffefd5", justify=CENTER)
passwordvar= StringVar()
entry1 = Entry(root, textvariable= passwordvar, justify=CENTER,relief=SUNKEN, cursor="pencil", takefocus=True )
Notice= Label(root, text="Your password must only be 5 characters long!!", font=notice, bg="#ffefd5", fg="#0000ff", justify=CENTER)
def callback(event):
if "<0>":
top = Toplevel(bg="#ffefd5")
top.title("Koala Encrypter")
popuptitle = Label(top, text="Your secret number must be between 1 and 9:", font=Body1, fg="red", bg="#ffefd5")
popuptitle.grid(row = 2,column=0, padx=5, pady = 50,sticky=N+S+E+W)
secret = Label(root, text="SECRET NUMBER: ", font=Body, bg="#ffefd5" , justify=CENTER,)
numbervar = StringVar()
entry2 = Entry(root, textvariable=numbervar , justify=CENTER,relief=SUNKEN,cursor="pencil", takefocus=True)
entry2.bind("<0>", callback)
Notice2 = Label(root, text="your secret number must be between 1 and 9!!!", font=notice, bg="#ffefd5", fg="#0000ff", justify=CENTER)
img = ImageTk.PhotoImage(Image.open("Koalalogo.jpg"))
panel = Label(root, image = img, relief=SUNKEN)
correct= Label(root, text="Check the below details \n\n Click \'yes\' if they are correct \n\n Click \'No\' to go back \n\n", font=Body1, bg="#ffefd5")
yourwebsite = Label(root, text="The Website is :", font=Body, bg="#ffefd5")#
website1 = Label(root, font=Body2, bg="#ffefd5",fg= "#00009C", textvariable = website)#
yourpassword = Label(root, text="Your Password is:", font=Body, bg="#ffefd5")
yournumber1= Label(root, font=Body2, bg="#ffefd5",textvariable = numbervar , fg= "#00009C", )
yourpassword1 = Label(root, font=Body2, bg="#ffefd5",textvariable = passwordvar , fg= "#00009C", )
yournumber= Label(root, text="Your Secret Number is:", font=Body, bg="#ffefd5")
def restart():
Titlemsg.grid_forget()
correct.grid_forget()
yourwebsite.grid_forget()
website1.grid_forget()
yourpassword.grid_forget()
yourpassword1.grid_forget()
yournumber.grid_forget()
yournumber1.grid_forget()
panel.grid_forget()
toolbar.grid_forget()
yes.grid_forget()
no.grid_forget()
entry.delete(0,END)
entry1.delete(0,END)
entry2.delete(0,END)
Titlemsg.grid( row=7, pady=25, sticky=N+S+E+W)
startpic.grid( row=10,pady=25, )
Head.grid( row=14, pady=25, columnspan=2, sticky=N+S+E+W)
toolbar.grid( row=21, )
end.grid(column =3, row=1, sticky=N+S+E+W)
begin.grid(column =2, row=1, sticky=N+S+E+W)
def start():
#entry.destroy()
#entry1.destroy()
#entry2.destroy()
toolbar.grid_forget()
Titlemsg.grid_forget()
begin.grid_forget()
Head.grid_forget()
startpic.grid_forget()
web.grid(row=3, column=0, sticky= W+E)
entry.grid( row=3, column=1, padx=50)
passw.grid(row=10, column=0)
Notice1.grid(row=4, sticky=N+S+E+W, columnspan=2)
entry1.grid(row=10, column=1)
Notice.grid(row=11,column=0, columnspan=2,)
secret.grid(row=13, column=0)
entry2.grid( row=13, column=1)
Notice2.grid( row=14,column=0, columnspan=2,)
panel.grid(row=20,columnspan=2, pady=70)
confirm.grid(column =1, row=1)
reset.grid(column =2, row=1)
end.grid(column =3, row=1)
toolbar.grid(row=21, column=0, columnspan=2)
Titlemsg.grid(row=0, column=0, columnspan=2, sticky=E+W)
def Reset():
entry.delete(0,END)
entry1.delete(0,END)
entry2.delete(0,END)
def clear_text():
#entry.destroy()
#entry1.destroy()
#entry2.destroy()
panel.grid_forget()
entry.grid_forget()
entry1.grid_forget()
entry2.grid_forget()
web.grid_forget()
Notice.grid_forget()
passw.grid_forget()
secret.grid_forget()
Notice1.grid_forget()
Notice2.grid_forget()
confirm.grid_forget()
reset.grid_forget()
toolbar.grid_forget()
Titlemsg.grid_forget()
Titlemsg.grid(row=0, column=0, columnspan=2, sticky=E+W)
correct.grid(row=1, column=0, columnspan=2, sticky=E+W)
yourwebsite.grid(row=2,column=0,sticky=E+W, pady=5)
website1.grid(row=2, column=1, padx=65,sticky=E+W, pady=5)
yourpassword.grid(row=4, column=0,sticky=E+W, pady=5)
yourpassword1.grid(row=4, column=1, padx=65,sticky=E+W, pady=5)
yournumber.grid(row=6, column=0,sticky=E+W, pady=5)
yournumber1.grid(row=6, column=1, padx=65,sticky=E+W, pady=5)
panel.grid(row=8, column=0, columnspan=2, pady=50)
toolbar.grid(row=10, column=0, columnspan=2)
yes.grid(column =1, row=1)
no.grid(column =2, row=1)
def popup():
top = Toplevel(bg="#ffefd5")
top.title("Koala Encrypter")
popuptitle = Label(top, text="Your password is:", font=Body1, fg="red", bg="#ffefd5")
popuptitle.grid(row = 2,column=0, padx=5, pady = 50,sticky=N+S+E+W)
pwd= Label(top, font=Body2, text="password", bg="#ffefd5", fg= "#00009C", ) #textvariable = newpassword ,
pwd.grid(row= 2, column=1,sticky=E+W,padx=15)
button = Button(top, text="OK", command=top.destroy, relief=RAISED )
button.grid(column =0,columnspan=2, row=4, sticky=N+S+E+W)
def helpmsg():
top = Toplevel(bg="#ffefd5")
top.title("Koala Encrypter")
popuptitle = Label(top, text="Koala series 1.0 - Koala Encrypter", font=Title, bg="#00FA9A", relief=RAISED,)
popuptitle.grid(row = 2,column=0, padx=5, pady = 50,sticky=N+S+E+W)
pwd= Label(top, font=Body, text="Free software to help you keep your acounts safe", bg="#ffefd5")
pwd.grid(row= 1,sticky=E+W,)
Titlems = Label(top, text="Koala Encrypter", font=Title, bg="#00FA9A", relief=RAISED,)
Titlems.grid( row=0, pady=25, sticky=N+S+E+W)
button = Button(top, text="OK", command=top.destroy, relief=RAISED )
button.grid(column =0,columnspan=2, row=4, sticky=N+S+E+W)
max_len = 5
def on_write(*args):
s = website.get()
if len(s) > max_len:
website.set(s[:max_len])
website.trace_variable("w", on_write)
max_len1 = 5
def on_write(*args):
s = passwordvar.get()
if len(s) > max_len1:
passwordvar.set(s[:max_len1])
passwordvar.trace_variable("w", on_write)
max_len2 = 1
def on_write(*args):
s = numbervar.get()
if len(s) > max_len2:
numbervar.set(s[:max_len2])
numbervar.trace_variable("w", on_write)
toolbar = Frame(root)
reset = Button(toolbar, text="Reset", width=6, command=Reset, cursor="cross", relief=RAISED, takefocus=True )
end = Button(toolbar, text="Quit" ,command=root.destroy, relief=RAISED, cursor="X_cursor", takefocus=True)
end.grid(column =3, row=1, sticky=N+S+E+W)
begin = Button(toolbar, text="Start Encrypting", command=start, relief=RAISED, cursor="star",takefocus=True )
begin.grid(column =2, row=1, sticky=N+S+E+W)
confirm = Button(toolbar, text="Next", command =clear_text, cursor="star", relief=RAISED,takefocus=True )
yes = Button(toolbar, text="Yes", command =popup, cursor="star", relief=RAISED,takefocus=True )
no = Button(toolbar, text="No", command =restart, cursor="pirate", relief=RAISED, takefocus=True )
toolbar.grid( row=21, )
menu = Menu(root)
root.config(menu=menu)
filemenu = Menu(menu)
menu.add_cascade(label="File", menu=filemenu)
filemenu.add_command(label="Restart", command=restart)
filemenu.add_separator()
filemenu.add_command(label="Exit", command=root.destroy)
helpmenu = Menu(menu)
menu.add_cascade(label="Help", menu=helpmenu, )
helpmenu.add_command(label="About...", command=helpmsg)
app = root
root.mainloop()
# add functionality, fix validation
To restrict the type/number of characters that can be typed into an entry widget, you can use the entry validatecommand. Here is an example to allow only letters and another one to restrict the entry to 4 digits:
from tkinter import Tk, Entry, Label
def only_letters(action, char):
if action == "1":
# a character is inserted (deletion is 0) allow the insertion
# only if the inserted character char is a letter
return char.isalpha()
else:
# allow deletion
return True
def only_numbers_max_4(action, new_text):
if action == "1":
return new_text.isdigit() and len(new_text) <= 4
else:
return True
root = Tk()
# register validate commands
validate_letter = root.register(only_letters)
validate_nb = root.register(only_numbers_max_4)
Label(root, text="Only letters: ").grid(row=0, column=0)
e1 = Entry(root, validate="key", validatecommand=(validate_letter, '%d', '%S'))
# %d is the action code and %S the inserted/deleted character
e1.grid(row=0, column=1)
Label(root, text="Only numbers, at most 4: ").grid(row=1, column=0)
e2 = Entry(root, validate="key", validatecommand=(validate_nb, '%d', '%P'))
# %P is the new content of the entry after the modification
e2.grid(row=1, column=1)
root.mainloop()
For more details on entry validation, see http://infohost.nmt.edu/tcc/help/pubs/tkinter/web/entry-validation.html

Calling lists when lists when lists are empty in TKinter

I wish to print from a list where the user enters an input and then has that input printed from a list. This however doesn't work without a blank string in the list as it says that the list is too short for the data to be shown in a label. I want for this to have the input printed immediately after pressing the continue button not after pressing the next button.
from tkinter import *
class Traveller:
def __init__(self, parent):
self.names = [""]
self.E_phone = "f"
self.E_name = "q"
self.count = 0
self.go = Frame(parent, width=500, height=450, bg="snow", pady=30, padx=10)
self.go.grid(row=1, column=0)
self.go.grid_propagate(0) # to reserve space required for frame
self.dataView = Frame(parent, width=500, height=500, bg="snow", pady=30, padx=10)
name = Label(self.go, text="Name:", bg="snow")
name.grid(row=1, column=0, sticky=E)
self.E_name = Entry(self.go, width=40)
self.E_name.grid(row=1, column=1, sticky=W, pady=4)
menuButton = Button(self.go, text="Continue", command=self.dataSave)
menuButton.grid(row=2, column=1, pady=4)
dataTitle = Label(self.dataView, text="Here is all of the inputted data:", bg="snow")
dataTitle.grid(row=2, column=0)
dataExit = Button(self.dataView, text="Return", command=self.returnT)
dataExit.grid(row=1, column=0, pady=5)
nextData = Button(self.dataView, text="Next", command=self.NData)
nextData.grid(row=4, column=0, pady=5)
prevData = Button(self.dataView, text="Previous", command=self.PData)
prevData.grid(row=4, column=1, pady=5)
self.everything = Label(self.dataView, text="The person" + self.names[self.count], bg = "snow")
self.everything.grid(row=3, column = 0)
def dataSave(self):
self.names.append(self.E_name.get())
self.go.grid_remove()
self.dataView.grid(row=1, column=0)
self.dataView.grid_propagate(0)
# clearing the entry boxes
self.E_name.delete(0, END)
def returnT(self):
self.dataView.grid_remove()
self.go.grid(row=1, column=0)
self.go.grid_propagate(0)
def NData(self):
self.count = self.count + 1
self.everything.configure(text = "The person " + self.names[self.count])
def PData(self):
if self.count >= 1:
self.count = self.count - 1
self.everything.configure(text = "The person " + self.names[self.count])
# main routine
if __name__ == "__main__":
root = Tk()
root.title("Traveller Details")
play = Traveller(root)
root.geometry("500x450+0+0")
root.mainloop()

python gui calculator, how should i force operands to work on number variables between them?

I got this GUI calculator working with two numbers and now I want to add a third number. I got it working with addition, then multiplication.. then adding a lot of numbers and subtracting/dividing after the adds or multiplying. Now if I try to get it to be a little bit more complicated I'm getting confused, because I may have set it up wrong.
The logic is something like this:
6 * 6 - 1 (calculators on windows don't do order of operations)
But in my script,
6 is first stored as evar.
Then the multiply function is called by the * button.
The multiply function appends evar to a list called FirstNumber.
The second 6 is now stored in evar.
The divide function is called by the / button.
The logic in divide is to set evar to FirstNumber.
Now the second 6 is set in firstNumber.
However, since firstNumber is a list, the sum of the two values are 12. However, I want it to be 36.
If I now subtract 1 on the calculator,I want it to be 35, but logically it's going to be 11.
The list doesn't know what operands are pressed between numbers, can someone steer me toward a way to do this?
import sys
import os
from tkinter import *
from operator import mul
class Calculator():
def __init__(self):
self.root = Tk()
self.root.title("Calculator")
self.frame1 = Frame(self.root)
self.frame2 = Frame(self.root)
self.frame3 = Frame(self.root)
self.frame4 = Frame(self.root)
self.frame5 = Frame(self.root)
self.frame1.pack(side=TOP)
self.frame2.pack(side=TOP)
self.frame3.pack(side=TOP)
self.frame4.pack(side=TOP)
self.frame5.pack(side=TOP)
self.evar = StringVar()
self.evar.trace("w", self.callback)
self.ent = Entry(self.frame1, textvariable = self.evar).pack(side=LEFT, padx = 10, pady= 10)
self.button7 = Button(self.frame2, text="7", bg="white", fg="black", bd=20, command=lambda : self.append_button(7))
self.button7.pack(side=LEFT)
self.button8 = Button(self.frame2, text="8", bg="white", bd=20, fg="black", relief="raised", command=lambda : self.append_button(8))
self.button8.pack(side=LEFT)
self.button9 = Button(self.frame2, text = "9", bg="white", bd=20, fg="black", relief="raised", command=lambda : self.append_button(9))
self.button9.pack(side=LEFT)
self.Divbutton = Button(self.frame2, text = "/", bg="white", bd=20, fg="black", relief="raised", command= self.divide)
self.Divbutton.pack(side=LEFT)
self.button4 = Button(self.frame3, text="4", bg="white", bd=20, fg="black", relief="raised", command=lambda : self.append_button(4))
self.button4.pack(side=LEFT)
self.button5 = Button(self.frame3, text="5", bg="white", bd=20, fg="black", relief="raised", command=lambda : self.append_button(5))
self.button5.pack(side=LEFT)
self.button6 = Button(self.frame3, text = "6", bg="white", bd=20, fg="black", relief="raised", command=lambda : self.append_button(6))
self.button6.pack(side=LEFT)
self.MultiplyButton = Button(self.frame3, text = "*", bg="white", bd=20, fg="black", relief="raised", command = self.multiply).pack(side=LEFT)
self.button1 = Button(self.frame4, text="1", bg="white", bd=20, fg="black", relief="raised", command=lambda : self.append_button(1))
self.button1.pack(side=LEFT)
self.button2 = Button(self.frame4, text="2", bg="white", bd=20, fg="black", relief="raised", command=lambda : self.append_button(2))
self.button2.pack(side=LEFT)
self.button3 = Button(self.frame4, text = "3", bg="white", bd=20, fg="black", relief="raised", command=lambda : self.append_button(3))
self.button3.pack(side=LEFT)
self.SubtractButton = Button(self.frame4, text = "-", bg="white", bd=20, fg="black", relief="raised", command = self.subtract).pack(side=LEFT)
self.button0 = Button(self.frame5, text = "0", bg="white", bd=20).pack(side=LEFT)
self.Clear = Button(self.frame5, text = "C", bg="white", fg="black", bd=20, command = self.clear).pack(side=LEFT)
self.AddButton = Button(self.frame5, text = "+", bg="white", bd=20, command = self.add).pack(side=LEFT)
self.EqualsButton = Button(self.frame5, text ="=", bg="white", bd=20, command = self.equals_button)
self.EqualsButton.pack(side=LEFT)
self.button = ""
self.total = 0
self.firstNumber = []
self.operand = ""
self.root.mainloop
self.count = 0
self.multiplyValue = 0
def clear(self):
self.evar.set("")
self.firstNumber = []
return self.firstNumber
def callback(self, *args):
print("Entry now %s" % self.evar.get())
def add(self):
self.firstNumber.append(int(self.evar.get()))
self.evar.set("")
self.operand = "+"
def subtract(self):
self.firstNumber.append(int(self.evar.get()))
self.evar.set("")
self.operand = "-"
def multiply(self):
self.firstNumber.append(int(self.evar.get()))
self.evar.set("")
self.operand = "*"
def divide(self):
self.firstNumber.append(int(self.evar.get()))
self.evar.set("")
self.operand = "/"
def create_button(self):
buttons = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
def append_button(self, val):
self.evar.set(self.evar.get() + str(val))
#when equals is presssed, perform a calculation based on the operand
def equals_button(self):
if self.operand == "+":
self.firstNumber.append(int(self.evar.get()))
result = sum(self.firstNumber)
elif self.operand == "-":
result = sum(self.firstNumber) - int(self.evar.get())
elif self.operand == "*":
self.multiplyValue = 1
for x in self.firstNumber:
self.multiplyValue *= x
result = self.multiplyValue * int(self.evar.get())
elif self.operand == "/":
result = sum(self.firstNumber) / int(self.evar.get())
self.evar.set(result)
Calc = Calculator()

Categories

Resources