0
我花了很多時間試圖用此代碼中的簡單入門小部件替換askinteger和askstring小部件。我相信有一種簡單的方法可以將來自入口小部件的信息傳遞給代碼中的其他函數,但我所研究和嘗試的所有內容都失敗了。任何幫助將是非常受歡迎的。我如何使Tkinter入門小部件數據可用於其他功能
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()
了'打印(弗雷德)可' (我刪除了)在'mainloop()'啓動後永遠不會被調用;在回調之後,'fred'的值被設置爲'entry'的值。如果你願意,你可以用它來更新標籤,或者做任何你喜歡的事情。 –