python - 如何访问python函数外部函数内部的变量?
问题描述
我有一个包含所有国家/地区的组合框,当用户选择一个国家/地区时,选择的国家/地区存储在函数内部的变量国家/地区中。但是,我需要访问函数之外的局部变量(国家)。有人可以帮我找到一种方法来访问声明它的函数之外的局部变量。
import tkinter as tk
from tkinter import ttk
from tkinter.messagebox import showinfo
root = tk.Tk()
root.geometry('500x500')
countries = ('afghanistan',
'albania',
'algeria',
'andorra',
'angola',
'anguilla',)
countries_cb = ttk.Combobox(root)
countries_cb['values'] = countries
countries_cb['state'] = 'readonly'
countries_cb.pack(fill='y', padx=5, pady=5)
def countries_changed(event):
msg = f'You selected {countries_cb.get()}!'
showinfo(message=msg)
country=(countries_cb.get()) #the local variable i want to access outside of the function
print(country)
countries_cb.bind('<<ComboboxSelected>>', countries_changed)
root.mainloop()
解决方案
如果您只想在函数外部读取局部变量的值,请从函数中返回它。像这样
def countries_changed(event):
msg = f'You selected {countries_cb.get()}!'
showinfo(message=msg)
country=(countries_cb.get()) #the local variable i want to access outside of the function
print(country)
country_local = countries_changed(event, country)
或者,如果您想在函数外部对其进行修改,请使用global
关键字。
country = ''
def countries_changed(event):
global country
msg = f'You selected {countries_cb.get()}!'
showinfo(message=msg)
country=(countries_cb.get()) #the local variable i want to access outside of the function
print(country)
print(country)
推荐阅读
- c# - SelectMany、GroupBy 和 First 的 LINQ 性能
- reactjs - (React Native) 仅淡入 Text 组件一次
- python - 真实加速度计数据的功率谱密度在 0 Hz 处显示异常值
- unicode - 以重音字符为键的 Common Lisp 哈希表
- python - 如何从 tika-python 库设置 TIKA_SERVER_ENDPOINT
- vba - 这个指针类型防水吗?
- apache-kafka - 无法消费来自 Kafka 集群的消息
- sql-server - SQL Server:需要在最后两个字符之前添加一个点
- javascript - 表单提交时如何获取html组件值?
- android - 无法在android中启用单击的禁用按钮