所以我收到错误 NameError:name' chris'没有定义,我怀疑它与全局变量和局部变量有关,但是我已经声明了' chris'作为函数中的全局变量。
下面是代码:
def ChrisFood():
global chris
chris = 1
FoodSelection()
def JoshFood():
global josh
josh = 1
FoodSelection()
def SamFood():
global sam
sam = 1
FoodSelection()
def DanielFood():
global daniel
daniel = 1
FoodSelection()
def JimFood():
global jim
jim = 1
FoodSelection()
def SeanFood():
global sean
sean = 1
FoodSelection()
def FoodSelection():
global FoodSelectionWindow
FoodSelectionWindow = Tk()
FoodSelectionWindow.configure(bg="black")
DateAdded = datetime.date.today
FoodSelectionPlaceHolder = Label(FoodSelectionWindow, text = "Food selection will be added in the third iteration")
FoodSelectionPlaceHolder.grid(columnspan=10)
if chris == 1:
with db:
cursor.execute(''' INSERT INTO 'Breakfast_History' (CaloriesTotal, DateAdded, PupilNames) VALUES (?,?,?)''',
([TotalCalories, DateAdded, "Chris"]))
elif josh == 1:
with db:
cursor.execute(''' INSERT INTO 'Breakfast_History' (CaloriesTotal, DateAdded, PupilNames) VALUES (?,?,?)''',
([TotalCalories, DateAdded, "Josh"]))
elif sam == 1:
with db:
cursor.execute(''' INSERT INTO 'Breakfast_History' (CaloriesTotal, DateAdded, PupilNames) VALUES (?,?,?)''',
([TotalCalories, DateAdded, "Sam"]))
elif daniel == 1:
with db:
cursor.execute(''' INSERT INTO 'Breakfast_History' (CaloriesTotal, DateAdded, PupilNames) VALUES (?,?,?)''',
([TotalCalories, DateAdded, "Daniel"]))
elif jim == 1:
with db:
cursor.execute(''' INSERT INTO 'Breakfast_History' (CaloriesTotal, DateAdded, PupilNames) VALUES (?,?,?)''',
([TotalCalories, DateAdded, "Jim"]))
elif sean == 1:
with db:
cursor.execute(''' INSERT INTO 'Breakfast_History' (CaloriesTotal, DateAdded, PupilNames) VALUES (?,?,?)''',
([TotalCalories, DateAdded, "Sean"]))
db.commit()
非常感谢任何帮助,
感谢。
答案 0 :(得分:0)
为某些内容定义全局变量并不为脚本中的所有函数定义它。这不是全球运作的方式。全局将局部变量更改为全局范围,请参阅:
x = 1
def foo():
x = 2 #<--- is a local variable x
def bar():
global x
x = 3 #<--- became the global x
print('changing global x')
foo()
print(x) # 1
bar() #changing global x
print(x) # 3
foo()
print(x) # 3
更改您的人员食物选择以改为通过此人:
def ChrisFood():
FoodSelection('chris')
def JoshFood():
FoodSelection('josh')
然后在你的FoodSelection
中让它接受一个参数并if
关闭它:
def FoodSelection(choice):
#what you have in here skipping to if
if choice == 'chris':
#do chris things
elif choice == 'josh':
#do josh things
如果可能的话,不要依赖global
。除了使用global