我有一个将坐标从一个系统转换为另一个系统的应用程序。源框架和目标框架使用许多相似的函数,例如组合框更改时执行的函数。 如何创建一次这些函数并在两个框架中使用它们 以下是在源系统中修改组合框地理格式时执行的这些函数的示例。我为目标系统写了同样的代码
def modified_combo_gf_src(choice):
chaine = chaine2 = chaine3 = ''
if choice == "deg":
chaine = "Latitude φ en °"
chaine2 = "Longitude λ en °"
if choice == "gon":
chaine = "Latitude φ en gon"
chaine2 = "Longitude λ en gon"
if choice == "rad":
chaine = "Latitude φ en rad"
chaine2 = "Longitude λ en rad"
if choice == "dms":
chaine = "Latitude φ en ° ' \""
chaine2 = "Longitude λ en ° ' \""
if choice == "pdms":
chaine = "Latitude φ en pdms"
chaine2 = "Longitude λ en pdms"
lbl_coord_x_src.configure(text=chaine)
lbl_coord_y_src.configure(text=chaine2)
我希望有一个函数来处理源选项卡和目标选项卡中的等效小部件。
如果您需要使用不同的标签,请将它们作为参数发送
def modified_combo_gf_src(choice, label_x, label_y):
# ... code ...
label_x.configure(text=chaine)
label_y.configure(text=chaine2)
如果您需要对不同元素使用转换,那么可以将转换移动到单独的函数
def convert(choice):
# ... code ...
return chaine, chaine2
def modified_combo_gf_src(choice, label_x, label_y):
tex1, text2 = convert(choice)
label_x.configure(text=text1)
label_y.configure(text=text2)
def other_function(choice...):
tex1, text2 = convert(choice)
# ... other code ... e.g. write in file
顺便说一句:您可以使用
f-string
来生成f"Latitude φ en {target}"
def modified_combo_gf_src(choice, label_x, label_y):
if choice == "deg":
target = "°"
elif choice == "gon":
target = "gon"
elif choice == "rad":
target = "rad"
elif choice == "dms":
target = "° ' \""
elif choice == "pdms":
target = "pdms"
else:
target = None
if target:
label_x.configure(text=f"Latitude φ en {target}")
label_y.configure(text=f"Longitude λ en {target}")
else:
print(f"ERROR: wrong choice {choice}")
你可以使用字典减少
if/elif
def modified_combo_gf_src(choice, label_x, label_y):
val = {
"deg": "°",
"gon": "gon",
"rad": "rad",
"dms": "° ' \"",
"pdms": "pdms"
}
target = val.get(choice)
if target:
label_x.configure(text=f"Latitude φ en {target}")
label_y.configure(text=f"Longitude λ en {target}")
else:
print(f"ERROR: wrong choice {choice}")
可读性较差
target = {"deg": "°", "gon": "gon", "rad": "rad", "dms": "° ' \"", "pdms": "pdms"}.get(choice)