I have spent many hours trying to replace the askinteger and askstring widgets with simple entry widgets in this code. I am sure there is a simple way to pass the information from the entry widget so that it can be used in other functions within the code, but everything I have researched and tried has failed. Any help will be very welcome.
from tkinter import *
from tkinter.simpledialog import askinteger
from tkinter.simpledialog import askstring
from random import randrange
def read_file(words_file):
with open(words_file, 'r') as f: # Read the text file
wordList = [] # Create an empty string called wordList
for line in f: # For every line in the text file
wordList += line.split() # Add another item to the list
f.close()
return wordList # Return the list
def select_word(wordList, word):
wordLength = 0
length = askinteger("Letters", "How Many Letters?") # Ask user for amount of letters
while wordLength != length:
wordNumber = randrange(0, len(wordList)) # Randomly select a number between 0 and length of wordList
word = wordList[wordNumber] # Select a word from the list using wordNumber
word = word.upper()
wordLength = len(word) # Calculate the length of the selected word
return word
def get_letter():
letter = askstring("Please enter a letter", "Which letter would you like to try?")
letter = letter.upper() # Convert letter to uppercase
return letter
This is the sort of things I have tried. I have also used stringvar.
from tkinter import *
master = Tk()
e = Entry(master)
e.pack()
e.focus_set()
def callback():
print (e.get())
global fred
fred = e.get()
print(fred)
return fred
b = Button(master, text="get", width=10, command=callback)
b.pack()
print(fred)
mainloop()
Thank you for your advice. I have now tried the following but still cannot get the print(fred) function to work. I'm sure this is a dumb mistake but I cannot see what I am doing wrong.
from tkinter import *
master = Tk()
e = Entry(master)
e.pack()
e.focus_set()
fred = '' # declare fred in the outer scope
def callback():
print (e.get())
fred = (e.get())
return fred # removed global statement as I understand they should be avoided
b = Button(master, text="get", width=10, command=callback)
b.pack()
print(fred)
mainloop()
You must define variable fred
in the outer scope in order to retrieve it. (there are other ways, but that is how your code is constructed):
from tkinter import *
master = Tk()
e = Entry(master)
e.pack()
e.focus_set()
fred = '' # declare fred in the outer scope
def callback():
print (e.get())
global fred
fred = e.get()
print(fred)
# return fred # as fred is global, returning it is optional
b = Button(master, text="get", width=10, command=callback)
b.pack()
mainloop()
fred
will contain the value retrieved from the entry
field, and be available for further processing
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.