Tkinter 中的3个 if 语句,怎么修改 ?
本帖最后由 dragov 于 2024-10-28 17:28 编辑from tkinter import *
root=Tk()
m=[{"designation":"北京万泉河","aspect":"hourglass"},{"designation":"天津海河","aspect":"error"},{"designation":"退出按钮","aspect":"info"}]
def tj():
p=Toplevel(root)
Button(p,text="这是天津的标签!").pack()
def bj():
q=Toplevel(root)
Button(q,text="这是北京的标签!").pack()
def secede():
root.destroy()
for i in range(len(m)):
n=Button(root,text=m["designation"],bitmap=m["aspect"],compound="bottom")
n.pack()
if "天津" in m["designation"] :
n.config(command=tj)
if "北京" in m["designation"] :
n.config(command=bj)
if "退出" in m["designation"] :
n.config(command=root.destroy)
mainloop()
在程序体中的 3 个 if 语句,使用起来有些别扭,怎么修改呢 ? 你可以使用字典来优化按钮和对应命令的映射,从而简化代码。下面是一个重构示例:
from tkinter import *
root = Tk()
# 修改为一个包含按钮标签和对应函数的字典
buttons = {
"天津": tj,
"北京": bj,
"退出": secede
}
# 创建按钮并绑定相应的命令
for label, command in buttons.items():
n = Button(root, text=label, command=command)
n.pack()
mainloop()
确保`tj`、`bj`和`secede`函数在`buttons`字典之前定义。
这样,代码会更清晰易读,方便维护。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 from tkinter import *
root = Tk()
m = [
{"designation": "北京万泉河", "aspect": "hourglass"},
{"designation": "天津海河", "aspect": "error"},
{"designation": "退出按钮", "aspect": "info"}
]
def on_button_click(button_text):
if "天津" in button_text:
tj()
elif "北京" in button_text:
bj()
elif "退出" in button_text:
secede()
def tj():
p = Toplevel(root)
Button(p, text="这是天津的标签!").pack()
def bj():
q = Toplevel(root)
Button(q, text="这是北京的标签!").pack()
def secede():
root.destroy()
for item in m:
n = Button(root, text=item["designation"], bitmap=item["aspect"], compound="bottom")
n.pack()
n.config(command=lambda: on_button_click(item["designation"]))
root.mainloop() 很cool的阳 发表于 2024-10-28 17:32
from tkinter import *
root = Tk()
您给出的这个程序,好似不行的!
页:
[1]