|
|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 dragov 于 2026-8-7 19:32 编辑
- from tkinter import *
- root=Tk()
- o=["东","南","西","北"]
- p=["red","blue"]
- def gyl():
- z=Toplevel(root)
- y=list()
- for i in range(len(o)):
- x=Button(z,text=o[i])
- x.pack()
- y.append(x)
- z.transient(root)
- z.grab_set()
- y[-1].focus_set()
- r=True
- def t():
- global r
- if r:
- y[1].config(background=p[0])
- r=False
- else :
- y[1].config(background=p[1])
- r=True
- y[1].after(2000,t)
- root.after(5000,t)
- Button(root,text="大暴雨",command=gyl).pack()
- mainloop()
复制代码
为什么提示 r 没有被定义呢 ?
- from tkinter import *
- root = Tk()
- directions = ["东","南","西","北"]
- color = ["red","blue"]
- def gyl():
- window = Toplevel(root)
- direction_buttons = list()
- for i in directions:
- button = Button(window,text=i)
- button.pack()
- direction_buttons.append(button)
- window.transient(root)
- window.grab_set()
- direction_buttons[-1].focus_set()
- flag = True
-
- def t():
- nonlocal flag
- if flag:
- direction_buttons[1].config(background=color[0])
- flag = False
- else:
- direction_buttons[1].config(background=color[1])
- flag = True
- direction_buttons[1].after(2000,t)
-
- root.after(5000,t)
-
- Button(root,text="大暴雨",command=gyl).pack()
- mainloop()
复制代码
核心错误:你的变量 r(即改后的 flag)不是全局变量,而是定义在一个函数内的局部变量
同时优化了你的变量名和 for 循环逻辑。(写一个有意义的变量名很重要!如果写不出英文变量名请使用汉语拼音。请不要o、p、r、t、x、y、z...排列)
|
|