Reputation: 169
I have written a script simulating a card game in Python where the user decides how many cards and how many piles of cards they want to play with. This input is controlled by following code where boundary_1
and boundary_2
give upper and lower limit in an integer interval and message is the user input:
def input_check(boundary_1, message, boundary_2):
run = True
while run:
try:
user_input =int(input(message))
if boundary_1 <= user_input <= boundary_2:
run = False
return user_input
else:
print ("Incorrect Value, try again!")
run = True
except ValueError:
print ("Incorrect Value, try again!")
I now want to try and make a GUI out of this card game using tkinter and I would therefore like to know if there's any way to save the user's input to a variable that could be sent into the input_check()
function above? I've read through some tutorials on tkinter and found the following code:
def printtext():
global e
string = e.get()
text.insert(INSERT, string)
from tkinter import *
root = Tk()
root.title('Name')
text = Text(root)
e = Entry(root)
e.pack()
e.focus_set()
b = Button(root,text='okay',command=printtext)
text.pack()
b.pack(side='bottom')
root.mainloop()
The following code simply prints the user's input in the Textbox, what I need is the user's input being checked by my input_check()
and then have an error message printed in the Textbox or the input saved to a variable for further use if it was approved. Is there any nice way to do this?
Many thanks in advance!
Upvotes: 1
Views: 12297
Reputation: 386010
The simplest solution is to make string
global:
def printtext():
global e
global string
string = e.get()
text.insert(INSERT, string)
When you do that, other parts of your code can now access the value in string
.
This isn't the best solution, because excessive use of global variables makes a program hard to understand. The best solution is to take an object-oriented approach where you have an "application" object, and one of the attributes of that object would be something like "self.current_string".
For an example of how I recommend you structure your program, see https://stackoverflow.com/a/17470842/7432
Upvotes: 2