最近,我在学习了一些关于Matlab的课程(主要集中在使用数学计算和绘图)之后开始使用python3,我仍然是一个初学者。 不过,我觉得创建一个计算器来计算pokemon的数量会很有趣,你可以用pokemon中可用的糖果来进化pokemon,然后使用Tkinter作为GUI。程序运行良好,效果良好。然而,我正在努力改进我的编码,这段代码包括许多嵌套的if和while语句,以及其他广泛的变量和参数使用。我想知道如何将这段代码改进为更“pythonic”的代码,或者这是否是创建这样一个程序的正确方法。 先谢谢你
from tkinter import *
from tkinter import messagebox
def EvolveCalc():
title = "Pokemon evolve calculator"
Poke = var.get()
Candies_total = Candies.get()
PAmount = Poke_amount.get()
if Poke == 'Pokemon':
messagebox.showinfo(title,
"Please select a Pokemon from the dropdown menu")
elif not PAmount.isdigit():
messagebox.showinfo(title, "Please only enter numbers")
elif not Candies_total.isdigit():
messagebox.showinfo(title, "Please only enter numbers")
else:
Candies_total = int(Candies.get())
PAmount = int(Poke_amount.get())
Evolve = int((Candies_total - 1) / (Pokedex[Poke] - 1))
Candies_needed = (PAmount * (Pokedex[Poke] - 1)) + 1
if PAmount < Evolve:
n = 0
while Candies_needed <= Candies_total:
n = n + 1
PAmount = PAmount + 1
Candies_needed = ((PAmount) * (Pokedex[Poke] - 1)) + 1
Candies_total = Candies_total + 3
Evolve2 = int((Candies_total - 1) / (Pokedex[Poke] - 1))
String1 = '''You have enough candies too evolve {0} {1},
but you only have {2} {1} in storage and thus can only
evolve {2} {1} If you catch {3} more {1} you can now
evolve {4} {1}.'''
messagebox.showinfo(title, String1.format(Evolve, Poke,
Poke_amount.get(),
n, Evolve2))
else:
m = 0
while Candies_total <= Candies_needed:
m = m + 1
PAmount = PAmount - 1
Candies_needed = ((PAmount) * (Pokedex[Poke] - 1)) + 1
Candies_total = Candies_total + 1
Evolve2 = int((Candies_total - 1) / (Pokedex[Poke] - 1))
String2 = 'Transfer {0} {1} so you can evolve a total of {2} {1}.'
messagebox.showinfo(title, String2.format(m, Poke, Evolve2))
root = Tk()
Pokedex = {'pidgey': 12,
'caterpie': 12,
'weedle': 12
}
root.title("Pokemon evolve calculator")
var = StringVar(root)
var.set('Pokemon')
choices = Pokedex.keys()
Pokemon = OptionMenu(root, var, *choices)
Pokemon.grid(column=0, row=1)
L1 = Label(root, text='Candies')
L1.grid(column=1, row=0)
Candies = Entry(root)
Candies.grid(column=1, row=1)
L2 = Label(root, text='Pokemon amount in storage')
L2.grid(column=2, row=0)
Poke_amount = Entry(root)
Poke_amount.grid(column=2, row=1)
Calculate = Button(root, text='Calculate', command=EvolveCalc)
Calculate.grid(column=1, row=2)
root.mainloop()
EvolveCalc
成为evolve_calc
Poke
和Candies_total
变成poke
和total_candies
这段代码可以简化
至
你的
Pokedex
可以格式化,这样更可读至
我无法运行你的代码,因为它的格式不正确。第一个
else
块完成后,空格关闭。其他建议:
相关问题 更多 >
编程相关推荐