如何在两个Python脚本间传递变量?

0 投票
1 回答
724 浏览
提问于 2025-04-18 11:28

我知道这个问题在论坛上讨论过很多次,我也看了很多相关内容,但我还是没有找到我需要的解决方案。

以下代码是我真实代码的一个非常简化的版本。

我的第一个脚本是这样的(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”中定义的窗口一样的窗口。我该如何将变量字典从一个脚本传递到另一个脚本呢?

1 个回答

0

kyssa1.py 文件中,要在模块的范围内声明 dictionary,也就是说要把它放在 type() 函数的外面。

kyssa2.py 文件中,你不需要使用 global,可以直接使用 dictionary

另外,打开文件时,使用 open() 函数,而不是 file()

datafile = open(dictionary)

撰写回答