我花了很多时间尝试使用此代码中的简单条目小部件替换askinteger和askstring小部件。我确信有一种简单的方法可以从条目小部件传递信息,以便它可以在代码中的其他函数中使用,但我研究和尝试的所有内容都失败了。我们非常欢迎任何帮助。
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
这是我尝试的那种东西。我也用过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()
感谢您的建议。我现在尝试了以下但仍然无法使print(fred)函数起作用。我确定这是一个愚蠢的错误,但我看不出我做错了什么。
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()
答案 0 :(得分:0)
您必须在外部作用域中定义变量fred
才能检索它。 (还有其他方法,但这就是你的代码的构造方式):
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
将包含从entry
字段中检索到的值,并可供进一步处理