python - ¿如何捕获您在文本框中输入的值并将它们保存在变量中以在程序的另一部分中使用它们?
问题描述
我希望我在 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()
解决方案
在函数内部创建的变量是本地的 - 您必须使用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)
推荐阅读
- here-api - H.ui.Control 与 React
- node.js - React 生产版本不适用于 IE 11
- python - 尝试加载测试 yaml 数据时“字符串索引必须是整数”
- python - 检测 STDIN 文件并阻止用户在 Python 中输入
- python-3.x - min() 函数无法正常工作,输出错误
- javascript - 有没有办法在 switch 语句中更改大小写?
- identityserver4 - 用户更新个人资料后如何更新 id_token
- python - 无法使用 conda env 在 Pycharm 中正常导入 opencv
- javascript - 不断收到此消息: [js] SyntaxError: missing ; 声明之前@(shell):1:8
- cordova - 背景地理位置不是可观察的