[英]Replace imported list of constants with another list in Python
My GUI application has two radiobuttons for changing the displayed language. 我的GUI应用程序有两个用于更改显示语言的单选按钮。 The words are assigned to the constants text1, text2, an so on, in two files:
在两个文件中,将单词分配给常量text1,text2等。
file_en.py: file_en.py:
text1 = 'Hello'
text2 = 'Goodbye'
...
file_fr.py: file_fr.py:
text1 = 'Bonjour'
text2 = 'Au revoir'
...
On start, the main module imports file_en or file_fr and everything is fine. 启动时,主模块导入file_en或file_fr,一切正常。 Now, when the user changes the language - can I immediately replace one imported constants assignment with another?
现在,当用户更改语言时-我可以立即将一个导入的常量分配替换为另一种吗?
I don't think that is possible, but I think I found a workaround for that. 我认为这不可能,但是我认为我找到了解决方法。 How about you have a function (
loadLang()
or something) that will change the language each time it is called, reading 2 different text files. 你有一个函数(
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
You should try this instead, it's must more simple and efficient. 您应该尝试使用它,它必须更加简单和高效。
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.