Tkinter Tutorial 7

Now we have the basic program working, we can look in to making a few enhancements. The main flaw with the above is If you don’t type anything you get a response If you simply type a string of numbers you get a response.grid Which clearly isn’t very helpful.

By adding the following code:-

def response():
 
	msg = "error : must be a text value"
 
	i = circletext.get()
	y = i.isdigit()
	if y == True:
		circletext.insert(0,(msg))
 
	else:	
		x = random.choice(RESPONSES)
		circletext2.delete(0, END) # clear prev output
		circletext2.insert(0,str(x)) # insert response

We are saying that if the text input box does not contain digits (isdigit) then ask for a text value.  To solve the other issue of the input being of zero length I added the following to the above

def response():
 
msg = "error : must be a text value"
 
i = circletext.get()
 
y = i.isdigit()
 
l = len(circletext.get())
 
print l
 
if y == True or l == 0:
 
circletext.insert(0,(msg))

So basically if y (the input) equals a numerical value OR is of zero length then throw up a request for a text value.

To get round the issue of not being able to clear the two boxes we add some more code

def clear():
	circletext.delete(0, END) # clear input box
	circletext2.delete(0, END) # clear output box
 
then add a new button
 
clear = Button( window, text ='Clear', command=clear)
 
and place it on the canvas
 
clear.grid(row = 4, column = 2, padx = 1, pady = 1)
 
As I have put this in column 2 then I have moved the exit button to 
column 3
 
exitbtn.grid(row = 4, column = 3, padx = 1, pady = 1)
 
Other than that, we should have 3 buttons. 
 
However if you run it then the buttons seem to be right on the edge 
so I have changed 
 
window.geometry("300x100") #wxh
window.geometry("310x100") #wxh
 
to add that little but more width

mnagic8 + 3 buttons

What you end up with should be something like this.