列表中的背景颜色问题

列表中的背景颜色问题

我正在尝试使用列表和在 LaTeX 中呈现一些 Python 代码,但在\lstinputlisting使用时遇到了一些问题。我无法真正描述它,因此我附上了一张图片:backgroundcolor\lstset

enter image description here

灰色块来自backgroundcolor\lstset如您所见,它没有完全覆盖代码,并且在行之间有一些额外的灰色文本,上面写着“bbrreeaakklliinneess”。即使我将颜色更改为白色,灰色文本也可以突出显示和复制。如果我从中删除,文本就会backgroundcolor消失\lstset,但背景是白色的。我用来定义的代码\lstset如下:

\definecolor{dkgreen}{rgb}{0,0.6,0}
\definecolor{gray}{rgb}{0.5,0.5,0.5}
\definecolor{mauve}{rgb}{0.58,0,0.82}
\definecolor{mygray}{rgb}{0.9,0.9,0.9}
\definecolor{LightGray}{gray}{0.95}
\lstset{frame=tb,
    language=Python,
    aboveskip=3mm,
    belowskip=3mm,
    showstringspaces=false,
    columns=flexible,
    basicstyle={\small\ttfamily},
    numbers=none,
    numberstyle=\tiny\color{gray},
    keywordstyle=\color{blue},
    commentstyle=\color{dkgreen},
    stringstyle=\color{mauve},
    backgroundcolor=\color{mygray}
    breaklines=true,
    breakatwhitespace=true,
    tabsize=3
}

有什么方法可以修复这个问题吗?

答案1

做就是了不是使用以下三个选项\lstset

%   breaklines=true, % <================================================
%   breakatwhitespace=true, % <=========================================
%   tabsize=3 % <=======================================================

因此,使用以下完整的 MWE(包filecontents用于获取带有 TeX 代码和 python 代码的编译 MWE):

\RequirePackage{filecontents}
\begin{filecontents*}{\jobname.py}
import random
n = 20
to_be_guessed = int(n * random.random()) + 1
guess = 0
while guess != to_be_guessed:
    guess = input("Neue Zahl: ")
    if guess > 0:
        if guess > to_be_guessed:
            print "Zahl zu groß"
        elif guess < to_be_guessed:
            print "Zahl zu klein"
    else:
        print "Schade, Sie geben also auf!"
        break
else:
    print "Glückwunsch! Das war's!"
\end{filecontents*}


\documentclass{scrartcl}

\usepackage{listings}
\usepackage{xcolor}

\definecolor{dkgreen}{rgb}{0,0.6,0}
\definecolor{gray}{rgb}{0.5,0.5,0.5}
\definecolor{mauve}{rgb}{0.58,0,0.82}
\definecolor{mygray}{rgb}{0.9,0.9,0.9}
\definecolor{LightGray}{gray}{0.95}
\lstset{%
    frame=tb,
    language=Python,
    aboveskip=3mm,
    belowskip=3mm,
    showstringspaces=false,
    columns=flexible,
    basicstyle={\small\ttfamily},
    numbers=none,
    numberstyle=\tiny\color{gray},
    keywordstyle=\color{blue},
    commentstyle=\color{dkgreen},
    stringstyle=\color{mauve},
    backgroundcolor=\color{mygray}
%   breaklines=true, % <================================================
%   breakatwhitespace=true, % <=========================================
%   tabsize=3 % <=======================================================
}


\begin{document}

Complete listing:
\lstinputlisting{\jobname.py}

\end{document}

得到结果:

wished result

相关内容