我知道这个问题在论坛中讨论,我已经阅读过很多内容,但我仍然没有我需要的解决方案。
以下代码是我的真实代码的非常简化版本。
我的第一个脚本是关注(kyssa1.py):
import os
import sys
def type():
global dictionary
dictionary="C:\Python27\Myprojects\physics.txt"
os.system("C:\Python27\Myprojects\kyssa2.py")
from Tkinter import *
t = Tk()
b = Button(t, text="Start", command = lambda:type())
b.pack(expand=Y)
t.mainloop()
我的第二个脚本(kyssa2.py)如下:
# -*- coding: utf-8 -*-
from kyssa1 import dictionary
def open():
global dictionary
global lines
global datafile
datafile = file(dictionary)
lines = [line.decode('utf-8').strip() for line in datafile.readlines()]
for i in lines:
text.insert(END, i)
open()
from Tkinter import *
root = Tk()
text = Text(root,font=("Purisa",12))
text.pack()
root.mainloop()
我想要做的是在kyssa2.py中打开文件physics.txt并使用此文本在函数open()中执行命令,但这并不是我想要的方式。当我点击“开始”按钮时会发生另一个窗口,就像“kyssa1.py”中定义的那样。我怎样才能将变量字典从一个脚本传递到另一个脚本?
答案 0 :(得分:0)
kyssa1.py
在模块范围内声明dictionary
,即type()
函数的外部。
您不需要在global
中使用kyssa2.py
,您可以直接参考dictionary
。
此外,要打开文件,请使用open()
而不是file()
:
datafile = open(dictionary)