Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/327.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jsf-2/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:获取复选框-最简单的方法_Python_User Interface_Tkinter - Fatal编程技术网

Python:获取复选框-最简单的方法

Python:获取复选框-最简单的方法,python,user-interface,tkinter,Python,User Interface,Tkinter,或者也许是懒惰的方式 我正在寻找一个python模块,它有一些内置的GUI方法来获得快速的用户输入,这是一个非常常见的编程案例。必须在Windows7上工作 我的理想案例 import magicGUImodule listOfOptions = ["option 1", "option 2", "option 3"] choosenOptions = magicGUImodule.getChecklist(listOfOptions,

或者也许是懒惰的方式

我正在寻找一个python模块,它有一些内置的GUI方法来获得快速的用户输入,这是一个非常常见的编程案例。必须在Windows7上工作

我的理想案例

import magicGUImodule
listOfOptions = ["option 1", "option 2", "option 3"]
choosenOptions = magicGUImodule.getChecklist(listOfOptions, 
                            selectMultiple=True, cancelButton=True)
这有点像原始输入,但是有一个GUI。因为这是一个常见的编程任务,所以一定有什么东西在那里


更新 @我没有把你的回答作为我问题的解决办法,这不是无礼的。我仍然希望能够在我正在编写的任何脚本中使用我的理想案例,而你的答案让我半途而废

我原以为可以将@alecxe的解决方案轻松地实现到一个模块中,但(对我来说)并没有那么简单

以下是我目前的模块:

# This serve as a module to get user input - the easy way!
# Some GUI selection
#from Tkinter import *
import Tkinter

master = Tkinter.Tk()
input = None
listbox = None

def chooseFromList(list, windowTitle="Choose from list", buttonText="Submit", selectMultiple=False, w=150, h=30):
    global listbox
    listbox = Tkinter.Listbox(master, selectmode=MULTIPLE if selectMultiple else SINGLE, width=w, height=h)
    listbox.master.title(windowTitle)
    for option in list:
        listbox.insert(0, option)
    listbox.pack()
    #listbox.selection_set(1)
    b = Tkinter.Button(master, command=callback(listbox), text=buttonText)
    b.pack()
    mainloop()

def callback(listbox):
    global listbox
    setInput(listbox.selection_get())
    master.destroy()    

def setInput(var):
    global input
    input = var

def getInput():
    global input
    return input
这是我的剧本

import GetUserInput
listOfOptions = ["option 1", "option 2", "option 3"]
choice = GetUserInput.chooseFromList(listOfOptions)
print choice.getInput()
但我只是得到了错误

无法调用“listbox”命令:应用程序已被销毁

我尝试了很多不同的选择,我认为这些选择可以解决这个问题(比如使用全局变量),但没有任何运气

更新2
@布拉布拉特罗斯给了我一个我一直在寻找的解决方案。

好吧,你不会很快得到什么,我不认为,几乎不管你看哪里。通常,您至少需要足够的样板文件来创建顶级窗口和/或小部件,以布局您实际关心的输入小部件


Python对GTK2和Qt(PyQt,现在使用4.X)都有很好的绑定,这两个都是非常高质量的跨平台GUI工具包,很容易入门。还有一些,wxWidgets是另一个突出的,但是其他的(包括内置的IMO)都已经过时了。

Tkinter是在Python内部构建的,它的复选框与您上面所述的形式非常相似,并且比大多数其他GUI模块更简单。请找一个好的教程(尽管需要一些更新)。官方文档是。

下面是一个使用
Tkinter
的简单示例(而不是使用带有多个选择的复选框
listbox
):

更新:

GetUserInput.py

from Tkinter import *


class GetUserInput(object):
    selection = None

    def __init__(self, options, multiple):
        self.master = Tk()

        self.master.title("Choose from list")

        self.listbox = Listbox(self.master, selectmode=MULTIPLE if multiple else SINGLE, width=150, height=30)
        for option in options:
            self.listbox.insert(0, option)
        self.listbox.pack()

        b = Button(self.master, command=self.callback, text="Submit")
        b.pack()

        self.master.mainloop()

    def callback(self):
        self.selection = self.listbox.selection_get()
        self.master.destroy()

    def getInput(self):
        return self.selection
主脚本:

from GetUserInput import GetUserInput

listOfOptions = ["option 1", "option 2", "option 3"]
print GetUserInput(listOfOptions, True).getInput()
希望有帮助。

Listbox 选中按钮+单选按钮 对多个选项使用Checkbutton,对单个选项使用Radiobutton

def chooseFromList(options, windowTitle="Choose from list", buttonText="Submit", selectMultiple=False, w=150, h=30):
    master = Tkinter.Tk()
    master.title(windowTitle)

    variables = []
    if selectMultiple:
        for option in options:
            v = Tkinter.StringVar()
            variables.append(v)
            Tkinter.Checkbutton(text=option, variable=v, onvalue=option, offvalue='').pack()
    else:
        v = Tkinter.StringVar()
        variables.append(v)
        for option in options:
            Tkinter.Radiobutton(text=option, variable=v, value=option).pack()

    Tkinter.Button(master, command=master.destroy, text=buttonText).pack()
    master.mainloop()
    return [v.get() for v in variables if v.get()]

我已经重复了@alecxe的答案,使用OOP以更健壮的方式管理GUI生命周期:

GUI元素 父脚本 为了处理可变参数,我添加了一些默认参数kwargs

PS:我使用的是Python 2.7,因此必须调整一些值(例如MULTIPLE->“MULTIPLE”)

模块正是您需要的:

import easygui as eg

question = "This is your question"
title = "This is your window title"
listOfOptions = ["option 1", "option 2", "option 3"]

choice = eg.multchoicebox(question , title, listOfOptions)
choice
将返回所选答案的列表


多选题使用
multchoicebox
,单选题使用
choicebox

从这里您可以得到准确的答案。只需单击此处

我就可以将其封装在个人python模块(magicGUImodule)的函数中-它基本上只需调用您的代码:)不客气,当然。我敢打赌,在任何python gui工具中,如
wx
qt
,它都会很简单。如何从Tkinter中挖掘多个参数?我想创建一个如下列表:mode=[SelectMode.SINGLE,SelectMode.MULTIPLE]//listbox=listbox(master,SelectMode=mode[True],width=w,height=h)我在创建模块时遇到了一些小的OOP问题。所以我不得不重新提出这个问题。。很抱歉,上一个解决方案使用类变量而不是全局每脚本变量,而且更具python风格和简洁性。对于其他容易调用的预定义方法,只需将此类用作模板。希望能有帮助。你说得对!我知道我不是唯一一个懒惰的python程序员。。非常感谢程序员们的欢呼!很高兴我能帮上忙。我知道几年前你们对此很高兴,但我只是唱了我自己的赞歌。最后,快速简单的东西!
def chooseFromList(options, windowTitle="Choose from list", buttonText="Submit", selectMultiple=False, w=150, h=30):
    master = Tkinter.Tk()
    master.title(windowTitle)

    variables = []
    if selectMultiple:
        for option in options:
            v = Tkinter.StringVar()
            variables.append(v)
            Tkinter.Checkbutton(text=option, variable=v, onvalue=option, offvalue='').pack()
    else:
        v = Tkinter.StringVar()
        variables.append(v)
        for option in options:
            Tkinter.Radiobutton(text=option, variable=v, value=option).pack()

    Tkinter.Button(master, command=master.destroy, text=buttonText).pack()
    master.mainloop()
    return [v.get() for v in variables if v.get()]
# This serve as a module to get user input - the easy way!
# Some GUI selection
import Tkinter

default_kwargs = { 
                  'selectmode'  : "single"          ,
                  'width'       : "150"             ,
                  'height'      : "30"              ,
                  'title'       : "Choose from list",
                  'buttonText'  : "Submit"  
}



class easyListBox:

    def __init__(self, options_list, **kwargs) :

        #options
        opt = default_kwargs #default options
        opt.update(kwargs) #overrides default if existant

        #Return value
        self.selected = 0;

        # GUI master object (life-time component)
        self.master = Tkinter.Tk()

        # Checklist with options
        listbox_options = { key: opt[key] for key in opt if key in['selectmode','width','height'] } #options slice for GUI
        self.listbox = Tkinter.Listbox(self.master, listbox_options)
        self.listbox.master.title(opt['title'])

        #Options to be checked
        for option in options_list:
            self.listbox.insert(0,option)
        self.listbox.pack()

        # Submit callback
        self.OKbutton = Tkinter.Button(self.master, command=self.OKaction, text=opt['buttonText'] )
        self.OKbutton.pack()

        #Main loop
        self.master.mainloop()

    # Action to be done when the user press submit
    def OKaction(self):
        self.selected =  self.listbox.selection_get()
        self.master.destroy() 

    # Return the selection
    def getInput(self):
        return self.selected
#import GetUserInput
import GUI as GetUserInput

listOfOptions = ["option 1", "option 2", "option 3"]
GUI_options = {'title' : "Custom title", 'selectmode' : 'multiple' }
#choice = GetUserInput.chooseFromList(listOfOptions)
elb = GetUserInput.easyListBox(listOfOptions, **GUI_options)
print elb.getInput()
import easygui as eg

question = "This is your question"
title = "This is your window title"
listOfOptions = ["option 1", "option 2", "option 3"]

choice = eg.multchoicebox(question , title, listOfOptions)