在這段代碼中,我正在撰寫一個函式來僅從包含相應 txt 檔案的檔案夾中獲取影像,因此當我在另一個函式中使用宣告的變數時,它會顯示錯誤
是因為全域變數在回圈內嗎?
import os
def open_image():
global img_file
EXT = ['.jpeg','.png','.jpg']
path = os.getcwd()
mydir = os.listdir(path)
for i in mydir:
k = os.path.splitext(i)
if k[1] in EXT:
img_file = k[0] k[1]
def image():
print(img_file)
image()
uj5u.com熱心網友回復:
通過將 img_file 移出您的函式來在全域范圍內宣告它。呼叫 open_image 來填充串列并呼叫 image() 函式來列印它。或者呼叫 image 函式中的 open_image,只要適合您的用例
import os
img_file=[]
def open_image():
EXT = ['.jpeg','.png','.jpg']
path = os.getcwd()
mydir = os.listdir(path)
for i in mydir:
k = os.path.splitext(i)
if k[1] in EXT:
img_file.append(k[0] k[1])
def image():
print(img_file)
open_image()
image()
uj5u.com熱心網友回復:
您需要在宣告全域變數的地方呼叫 open_image() 函式。
import os
def open_image():
global img_file
EXT = ['.jpeg','.png','.jpg']
path = os.getcwd()
mydir = os.listdir(path)
for i in mydir:
k = os.path.splitext(i)
if k[1] in EXT:
img_file = k[0] k[1]
open_image()
def image():
print(img_file)
image()
uj5u.com熱心網友回復:
Python:要在另一個函式中使用區域變數,我們使用 func
def func():
func.name = "Ali Axghar"
func()
print(func.name)
輸出:Ali Axghar
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/494241.html
上一篇:按時間排列的行星位置
