[英]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.