为再函数内部实现对全局变量的修改,python中包含global、nonlocal关键字。
关于global关键字的使用:
1)global关键字修饰变量后标识该变量是全局变量;
2)函数内部不改变变量值,函数外部变量申明时使用global关键字;函数内部可直接使用
3)函数内部改变变量值,需要重申明变量为global,否者报错。
关于nonlocal关键字使用:
1)nonlocal关键字,nonlocal关键字修饰变量后标识该变量是上一级函数中的局部变量,如果上一级函数中不存在该局部变量,nonlocal位置会发生错误。
import tkinter
import tkinter.messagebox
def main():
global flag
flag = True
def change_label_text():
global flag
flag = not flag
color, msg = ('red', 'Hello, world!')\
if flag else ('blue', 'Goodbye, world!')
label.config(text=msg, fg=color)
def confirm_to_quit():
if tkinter.messagebox.askokcancel('温馨提示', '确定要退出吗?'):
top.quit()
top = tkinter.Tk()
top.geometry('240x160')
top.title('小游戏')
label = tkinter.Label(top, text='Hello, world!', font='Arial -32', fg='red')
label.pack(expand=1)
panel = tkinter.Frame(top)
button1 = tkinter.Button(panel, text='修改', command=change_label_text)
button1.pack(side='left')
button2 = tkinter.Button(panel, text='退出', command=confirm_to_quit)
button2.pack(side='right')
panel.pack(side='bottom')
tkinter.mainloop()
if __name__ == '__main__':
main()