首页 > 解决方案 > ¿如何捕获您在文本框中输入的值并将它们保存在变量中以在程序的另一部分中使用它们?

问题描述

我希望我在 inputValue 变量中获得的值可以在代码的另一部分中使用,但是当窗口被破坏时,输入的值会丢失

from tkinter import *
root=Tk()
def retrieve_input():
    inputValue=textBox.get("1.0","end-1c")
    print(inputValue)

def Close():
    root.quit()

def Ambas():
    retrieve_input()
    Close()

textBox=Text(root, height=2, width=10)
textBox.pack()
buttonCommit=Button(root, height=1, width=10, text="Aceptar", command=lambda: Ambas())
#command=lambda: retrieve_input() >>> just means do this when i press the button
buttonCommit.pack()
mainloop()

标签: pythontkinter

解决方案


在函数内部创建的变量是本地的 - 您必须使用global将值分配给全局变量

#from tkinter import * # PEP8: `import *` is not preferred
import tkinter as tk

# --- functions ---

def ambas(): # PEP8: `lower_case_names` for functions and variables
    global input_value

    input_value = text_box.get("1.0", "end-1c")
    print('inside ambas:', input_value)
    root.destroy()

# --- main ---

root = tk.Tk() # PEP8: spaces around `=`

text_box = tk.Text(root, height=2, width=10)
text_box.pack()

button_commit = tk.Button(root, height=1, width=10, text="Aceptar", command=ambas)
button_commit.pack()

root.mainloop()

print('after mainloop:', input_value)

推荐阅读