首页 > 解决方案 > 如何访问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()  

标签: pythonvariablescombobox

解决方案


如果您只想在函数外部读取局部变量的值,请从函数中返回它。像这样

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)

推荐阅读