从Radiobutton获取输入

2024-04-20 12:18:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我用的是Tkinter和图形.py(Tkinter上的一个包装器)用GUI创建一个相当基本的集成器(在图形下查找区域)。到目前为止,积分器的主“控制面板”与实际图形是分开的(这是通过使用图形.py). 我使用Tkinter的Radiobutton()来选择积分类型(左矩形、右矩形、梯形或辛普森近似)。在

我的问题是我无法从单选按钮获得输出。我使用的是TutorialsPoint: Tkinter Radiobutton中的示例。在

这是我的代码:

class FunctionInput:
        def __init__(self, master, window, items):
            self.window = window
            self.items = items
            self.runProgram = True
            self.typeChoice = tk.StringVar()
            self.frame = tk.Frame(master)
            self.typeFrame = tk.Frame(self.frame)
            self.quitButton = tk.Button(self.frame, text = 'Quit', command = self.frame.quit)
            self.optLabel = tk.Label(self.frame, text = 'Type of Approximation: ')
            self.optL = tk.Radiobutton(self.typeFrame, text = 'Left Rectangular', variable = self.typeChoice, value = 'l')
            self.optR = tk.Radiobutton(self.typeFrame, text = 'Right Rectangular', variable = self.typeChoice, value = 'r')
            self.optT = tk.Radiobutton(self.typeFrame, text = 'Trapezoidal', variable = self.typeChoice, value = 't')
            self.optS = tk.Radiobutton(self.typeFrame, text = 'Simpsons Rule', variable = self.typeChoice, value = 's')
            self.optL.grid(row = 1, column = 1, padx = 5, pady = 5)
            self.optR.grid(row = 1, column = 2, padx = 5, pady = 5)
            self.optT.grid(row = 2, column = 1, padx = 5, pady = 5)
            self.optS.grid(row = 2, column = 2, padx = 5, pady = 5)
            self.optLabel.grid(row = 4)
            self.typeFrame.grid(row = 5)
            self.quitButton.grid(row = 6)
            # there were numerous other widgets and frames, but I only included the relevant ones
            self.frame.grid()

        def getInput(self):
            type_integration = self.typeChoice.get()
            self.frame.quit()
            return type_integration


def main():
    # some other code, win and axisLabels are defined prior to this
    root = tk.Tk(className = ' Function Grapher')
    app = FunctionInput(root, win, axisLabels)
    root.rowconfigure(0, weight = 1)
    root.columnconfigure(0, weight = 1)
    root.mainloop() # there is a button to exit the mainloop in my GUI
    typeIntegration = app.getInput()
    print typeIntegration # trying to debug it

if __name__ == '__main__': main()

但是,它不打印变量。打印不是一个字符串,所以不是一个空的执行问题。root.mainloop()不会陷入无限循环,因为我的GUI中有一个按钮(这里没有显示,因为它是无关的)退出它。没有出现错误,所以我猜问题出在设置变量的选项上。非常感谢任何帮助。在

另外,附带说明一下,每当我运行程序时,“右矩形”、“梯形”和“辛普森规则”单选按钮都灰显,如下所示:

如果我点击其中一个单选按钮,这种灰色会消失,但在那之前,它会一直保持。如果有办法解决这个问题,请告诉我。在

谢谢!在


Tags: textself图形valuetkinterrootvariable按钮
2条回答

问题是,由于我使用了多个其他小部件,我不得不将StringVar()smaster参数设置为self.typeFrame

^{1}$

另外,正如@A.Rodas所说,为了摆脱灰色,我做了:

^{pr2}$

我还没有看到“退出”按钮的部分,但您的代码是这样做的:

  1. 启动主循环
  2. exit按钮的事件处理程序调用root.quit()
  3. getInput中,检索值并调用self.frame.quit()

首先调用kinter循环的kinter函数,然后再调用kinter循环的值。这是一个基于您的代码的有效示例:

^{1}$

相关问题 更多 >