如何在python中创建跨模块变量

时间:2013-11-20 02:34:16

标签: python python-2.7 tkinter ttk

我每次用户点击菜单上的“new”时都会尝试添加一个新的Frame,但我似乎无法以某种方式导入核心程序将Frame添加到笔记本中。这是我的调试错误:

Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Python27\lib\lib-tk\Tkinter.py", line 1470, in __call__
return self.func(*args)
File "C:\Users\Owner\Desktop\HTML IDE\UI_functions.py", line 8, in UI_add_frame
UI_notebook.add(UI_f2,text = "test")
NameError: global name 'UI_notebook' is not defined?

这是我的代码:

import Tkinter
from Tkinter import *
import ttk
import UI_functions

root = Tkinter.Tk()
root.title("HTML IDE coded in Python")
w = 515
h = 590
sw = root.winfo_screenwidth()
sh = root.winfo_screenheight()
x = (sw - w)/2
y = (sh - h)/2
root.geometry('%dx%d+%d+%d' % (w, h, x, y))

#Menu contents
UI_menu = Menu(root)
filemenu = Menu(UI_menu, tearoff=0)
filemenu.add_command(label="New",command = UI_functions.UI_add_frame)
filemenu.add_command(label="Open")
filemenu.add_command(label="Save")
filemenu.add_command(label="Save as...")
filemenu.add_command(label="Close")

filemenu.add_separator()

filemenu.add_command(label="Exit", command=root.quit)
UI_menu.add_cascade(label="File", menu=filemenu)
editmenu = Menu(UI_menu, tearoff=0)
editmenu.add_command(label="Undo")

editmenu.add_separator()

editmenu.add_command(label="Cut")
editmenu.add_command(label="Copy")
editmenu.add_command(label="Paste")
editmenu.add_command(label="Delete")
editmenu.add_command(label="Select All")

UI_menu.add_cascade(label="Edit", menu=editmenu)
helpmenu = Menu(UI_menu, tearoff=0)
helpmenu.add_command(label="Help Index")
helpmenu.add_command(label="About...")
UI_menu.add_cascade(label="Help", menu=helpmenu)

#Notebook contents
global UI_notebook
UI_notebook = ttk.Notebook(root)
UI_notebook.pack(fill="both", expand="yes")

#Nake frames for the notebook
UI_f1 = ttk.Frame()

#Add the frames to notebook
UI_notebook.add(UI_f1,text = "new")

root.config(menu=UI_menu)
root.mainloop()

这是该计划的核心,这是“UI_functions”模块:

#Functions for the core program
import ttk
import Tkinter

#Add new notebook tab when user clicks "new"
def UI_add_frame():
   UI_f2 = ttk.Frame()
   UI_notebook.add(UI_f2,text = "test")

2 个答案:

答案 0 :(得分:1)

UI_functions.py中,您使用core.pyUI_notebook)中的元素,core.py中使用来自UI_functions.pyUI_add_frame)的元素,这样您就可以了对"cross imports"有疑问。

最好这样做:

import ttk
import Tkinter

def UI_add_frame(some_notebook):
    UI_f2 = ttk.Frame()
    some_notebook.add(UI_f2, text = "test")

并且使用lambda

filemenu.add_command(label="New",command = lambda:UI_functions.UI_add_frame(UI_notebook))

这种方式模块不使用在程序中动态创建的变量,因此模块是独立的。你还没有"cross imports"

答案 1 :(得分:0)

将UI_functions.py更改为:

import ttk
import Tkinter
import mb # whatever filename you chose

def UI_add_frame():
    UI_f2 = ttk.Frame()
    mb.UI_notebook.add(UI_f2, text = "test")