我目前是一名獲得計算機科學學士學位的學生,我正在寫作一個蟒蛇計劃,在閒暇時間,我必須幫助我學習西班牙語。這絕對不是我要出版的任何奢侈節目或任何東西,只是爲了讓我玩得開心。我剛剛學習了Tkinter的python編程的基本GUI結構,我只是試圖指出正確的方向來優化我的代碼,使其更小,看起來不那麼基本。我有3500行的代碼,到目前爲止,所以我不會上傳完整的代碼,但這裏幾乎是我整個程序的結構如何優化我的西班牙語翻譯計劃的代碼?
def _months(self):
#Framework for the Month Window
Frame.__init__(self)
self.master.title("Months")
self.grid()
labelfont = ("times", 18, "bold")
homefont = ("times", 10, "bold")
self._monthMenuImage = PhotoImage(file = 'mexicoWater.gif')
self._monthBackgroundLabel = Label(self, image = self._monthMenuImage)
self._monthBackgroundLabel.place(x = 0, y = 0)
self.grid_propagate(0)
self["height"] = 600
self["width"] = 800
#January button
self._januaryButton = Button(self, text = "January",
command = self._switchJanuary)
self._januaryButton.config(font = labelfont, bg = self.water2)
self._januaryButton.config(height = 0, width = 10)
self._januaryButton.place(x = 65, y = 325)
#February button
self._februaryButton = Button(self, text = "February",
command = self._switchFebruary)
self._februaryButton.config(font = labelfont, bg = self.water2)
self._februaryButton.config(height = 0, width = 10)
self._februaryButton.place(x = 315, y = 325)
#March button
self._marchButton = Button(self, text = "March",
command = self._switchMarch)
self._marchButton.config(font = labelfont, bg = self.water2)
self._marchButton.config(height = 0, width = 10)
self._marchButton.place(x = 565, y = 325)
的"command = self._switch...."
導致不同的方法,如
def _switchJanuary(self):
if self._januaryButton["text"] == "January":
self._januaryButton.config(bg = self.water1)
self._januaryButton["text"] = "Enero"
else:
self._januaryButton["text"] = "January"
self._januaryButton.config(bg = self.water2)
def _switchFebruary(self):
if self._februaryButton["text"] == "February":
self._februaryButton.config(bg = self.water1)
self._februaryButton["text"] = "Febrero"
else:
self._februaryButton["text"] = "February"
self._februaryButton.config(bg = self.water2)
def _switchMarch(self):
if self._marchButton["text"] == "March":
self._marchButton.config(bg = self.water1)
self._marchButton["text"] = "Marzo"
else:
self._marchButton["text"] = "March"
self._marchButton.config(bg = self.water2)
「self.water1」和「self.water2」只是早些時候我聲明爲類變量的很酷的藍色。
這是我整個代碼的基本結構,包括月份,日期,數字等。我只是試圖找到一種讓代碼更小的方法,因爲我想爲程序添加很多不同的功能,而不需要一百萬行。我被告知要使用字典,在字典中我可以訪問鍵值來翻譯單詞,而不必讓每個按鈕導致不同的方法,但我迷了路。任何幫助將不勝感激。感謝您的時間!
那麼你必須現在決定什麼對你更重要,如果你想要簡單易讀的代碼,你不需要改變太多。如果你真的想要一個小巧的小巧的可讀性小於你可以開始在一個配置行中定義你的屬性。例如,您可以寫self._marchButton.config(bg = self.water1) self._marchButton [「text」] =「Marzo」'您可以編寫'self._marchButton.config(bg = self.water1,text =「馬佐「)'所以你保存了2行,這使得24行。或者你可以鏈接方法:'self.grid_propagate(0)。配置(寬度= 800,高度= 600)' – VRage
真棒,感謝您的快速響應。這有助於縮短一點。我只是想在開始修復之前先獲得程序的基本結構。我只知道有一種更簡單的方法可以將我想要翻譯成列表或字典的所有單詞,並從按鈕中調用它們,而不是讓每個命令都指向它自己的方法。但我不知道我該怎麼做。 –
如果你的代碼工作正常,應該詢問[Code Review Stack Exchange](http://codereview.stackexchange.com/) –