【发布时间】:2019-04-29 11:28:07
【问题描述】:
计划总结
我正在制作一个基于 python 的文本处理程序。在这里,我使用以下 Tkinter 小部件,其 GUI 具有以下名称:
- 文本小部件 > “text_input”
- 文本小部件 > “text_output”
- CheckButton 小部件 > “checkButton_tense”
- 按钮小部件 > “button_analysis”
现在我想让我的程序按以下顺序运行。
- 从“text_input”中获取文本。
- 单击“button_analysis”并在“text_output”中显示输出,在其他类中执行一些基本文本处理。
- 但如果单击/选中“checkButton_tense”小部件。然后它还应该执行 Tense Inspection 以及基本的文本处理,否则它应该只执行基本的文本处理。
- 以上操作编号。 3 应在单击“button_analysis”检查“checkButton_tense”小部件的状态并在“text_output”中显示输出后执行
问题/错误
现在,当我在我的 Tkinter 按钮“button_analysis”小部件的“command=lambda:”中使用 if 语句来检查“checkButton_tense”的状态时,它给了我错误。我尝试了很多方法,但它不起作用。
我已经尝试过here 提到的解决方案。但是当我尝试任何这样的解决方案时,我无法在“text_output”小部件中显示我的文本,因为它位于不同的 python 方法“main_gui_layout”中。我还尝试了堆栈溢出此处给出的许多其他解决方案,但没有发现任何相同的解决方案。请在上述问题和以下代码的上下文中指导我。
代码
from tkinter import *
from Examples import Examples
from TextAnalysis import PerformTextAnalysis
class MyGui:
useExamples = Examples()
performTextAnalysis = PerformTextAnalysis()
def __init__(self, master):
self.main_gui_layout(master)
def main_gui_layout(self, master):
# InputBox to get the input Text.
text_input = Text(master, bd=1, height=15, width=100)
text_input.insert('end', self.useExamples.example2)
text_input.pack(side=TOP)
# OutputBox to show the processed Text.
text_output = Text(master, bd=1, height=15, width=100)
text_output.pack(side=TOP)
# CheckButton: it will perform tense analysis if checked/clicked
tenseCheck_clicked = IntVar()
checkButton_tense = Checkbutton(master, text="Tense Inspection", variable=tenseCheck_clicked,
bg='#9aa7bc')
checkButton_tense.var = tenseCheck_clicked
checkButton_tense.pack(side=TOP)
# Analysis Button: it will process text and show in output.
# It will also perform Tense Analysis if Above "checkButton_tense" is check/active.
button_analyse = Button(master, text="Analyse Requirements", width=20,
command=lambda:
[
self.performTextAnalysis.get_userReqiurement(
str(text_input.get('1.0', 'end'))),
if tenseCheck_clicked == 1:
ans = self.performTextAnalysis.performBasicAnalysis(),
self.performTextAnalysis.performTenseAnalysis(),
text_output.insert(END, ans)
else:
self.performTextAnalysis.performBasicAnalysis()
])
button_analyse.pack(side=TOP)
【问题讨论】:
-
为什么不把你的 if-else 语句放在
button_analyse的回调函数中呢?然后您可以跟踪checkbutton_tense是否被选中。 -
不要构建复杂的 lambda 函数。那不是他们的目的。只需将所有内容移至标准函数,然后使用按钮调用该函数。就这么简单。
-
@FrainBr33z3 感谢您的回复。但问题是 -> 当我们进行回调时,我们需要为几乎所有回调创建新方法。但是当我制作不同的功能时,我还必须一次又一次地将 tk.root 的“主”对象传递给扰乱 GUI 布局的新方法。我不知道如何解决它。我按照这种方式进行回调 [Link] (effbot.org/zone/tkinter-callbacks.htm) 但它扰乱了我的 GUI。
-
@Mike-SMT 也感谢您的回复。当我删除 lambdas。然后我很难使用单个命令执行多个操作。当我使用回调创建不同的函数时,我的 GUI 布局会受到干扰。如何在不使用 return 的情况下将函数内的对象调用到其他函数。我很迷惑。完全模棱两可,不知道如何在这里详细说明。
标签: python if-statement button tkinter lambda