[英]Replace imported list of constants with another list in Python
我的GUI應用程序有兩個用於更改顯示語言的單選按鈕。 在兩個文件中,將單詞分配給常量text1,text2等。
file_en.py:
text1 = 'Hello'
text2 = 'Goodbye'
...
file_fr.py:
text1 = 'Bonjour'
text2 = 'Au revoir'
...
啟動時,主模塊導入file_en或file_fr,一切正常。 現在,當用戶更改語言時-我可以立即將一個導入的常量分配替換為另一種嗎?
我認為這不可能,但是我認為我找到了解決方法。 你有一個函數( loadLang()
怎么樣,該函數每次被調用時都會更改語言,讀取2個不同的文本文件。
text1=''
text2=''
activeLang = 'en' #current language
def loadLang(lang):
global text1
global text2
global activeLang
if activeLang != lang: #check if current language is
already what user wants
file=open("file_" + lang + ".txt", "r") #open file
#assuming contents are same as your post without spaces
text1=file.readline().rstrip()
text2=file.readline(2).rstrip() #read line and remove
\n
return
#main code
#idk how you're doing it so:
def onClick():
global text1
global text2
if 'fr' in button.text:
loadLang('fr')
button1.text = text1
button2.text = text2
您應該嘗試使用它,它必須更加簡單和高效。
import file_en
import file_fr
text1=""
text2=""
activeLang = 'en'#current language
def onClick():
global text1
global text2
global activeLang
if activeLang == 'en':
text1 = file_fr.text1
text2 = file_fr.text2
elif activeLang == 'fr': #check lang
text1 = file_en.text1
text2 = file_en.text2
else:
# Error handling goes here
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.