简体   繁体   English

如果在 Python 中选择了下拉列表中的项目,则提示用户输入

[英]Prompt user for input if item on drop-down list is selected in Python

I have a GUI in python that, amongst other things, let's the user choose items from a dropdown menu (I used the combobox feature from tkinter).我在 python 中有一个 GUI,除其他外,让用户从下拉菜单中选择项目(我使用了 tkinter 的组合框功能)。

I wish to have it so that when the item "Custom" is select, an input box appears to ask the user what their custom number would be.我希望拥有它,以便在选择“自定义”项时,会出现一个输入框,询问用户他们的自定义编号是什么。 I don't want to have to use a button for the box to appear, but somehow have it so that as soon as custom is selected, the input box appears.我不想使用按钮来显示框,但不知何故,只要选择自定义,输入框就会出现。 I tried first with while loops but I can't get it to work, same with if statements :s我首先尝试使用 while 循环,但无法使其正常工作,与 if 语句相同:s

I also tried using the askinteger() method that I found here ( http://effbot.org/tkinterbook/tkinter-entry-dialogs.htm ) but none of the combinations I came up with worked (I am very new at Python and am still learning so excuse my obvious mistakes).我还尝试使用我在这里找到的 askinteger() 方法( http://effbot.org/tkinterbook/tkinter-entry-dialogs.htm ),但我想出的组合都没有奏效(我对 Python 和我还在学习所以请原谅我明显的错误)。

Here is my code for the GUI :这是我的 GUI 代码:

from tkinter import *
from tkinter.ttk import *
from tkinter import filedialog
from tkinter import StringVar
from tkinter import messagebox
from tkinter import simpledialog


class MyGUI:
    def __init__(self, master):

        self.master = master
        master.title("Intent/Interpretation Check")

        self.runlabel = Label(master, text="RunID :")
        self.runlabel.grid(row=0, column=0)

        self.runentry = Entry(master)
        self.runentry.grid(row=1, column=0, padx=25)

        self.checklabel = Label(master, text="Check type :")
        self.checklabel.grid(row=0, column=1)

        self.typeselect = Combobox(master)
        self.typeselect['values']=("Intent Score", "Interpretation Score")      
        self.typeselect.grid(row=1, column=1, padx=25)

        self.limitlabel = Label(master, text="Fails if score is below :")
        self.limitlabel.grid(row=0, column=2, padx=25)

        self.limitselect = Combobox(master)
        self.limitselect['values']=(1000, 5000, "Custom")       
        self.limitselect.grid(row=1, column=2, padx=25)
        if self.limitselect.get() != "Custom":
            self.limit = self.limitselect.get()
            pass
        else:
            self.askinteger("Custom limit", "Please enter a number from 1 to 10000", minvalue=1, maxvalue=10000)

        self.submitbutton = Button(master, text="Submit", command=self.checkstatus)
        self.submitbutton.grid(row=1, column=3, padx=25, pady=5)

root = Tk()
root.geometry("+600+300")
my_gui = MyGUI(root)
root.mainloop()

Thank you very much in advance !非常感谢您提前!

You need to have a Bool that tells when to show the new input should be shown.您需要有一个 Bool 来告诉何时应该显示新输入。 You also need to be constantly polling the ComboBox to see if it's value is equal to "Custom".您还需要不断轮询 ComboBox 以查看它的值是否等于“自定义”。 This is what I came up with in about 3 minutes.这是我在大约 3 分钟内想到的。

I didn't try to make the GUI look pretty, just a functional example.我没有试图让 GUI 看起来很漂亮,只是一个功能性的例子。

from tkinter import *
from tkinter.ttk import *

class Gui:

    def __init__(self):
        self.root = Tk()

        # Set up the Combobox
        self.selections = Combobox(self.root)
        self.selections['values'] = ['Apples', 'Oranges', 'Blueberries', 'Bananas', 'Custom']
        self.selections.pack()

        # The Entry to be shown if "Custom" is selected
        self.custom_field = Entry(self.root)
        self.show_custom_field = False

        # Check the selection in 100 ms
        self.root.after(100, self.check_for_selection)

    def check_for_selection(self):
        '''Checks if the value of the Combobox equals "Custom".'''


        # Get the value of the Combobox
        value = self.selections.get()

        # If the value is equal to "Custom" and show_field is set to False
        if value == 'Custom' and not self.show_custom_field:

            # Set show_field to True and pack() the custom entry field
            self.show_custom_field = True
            self.custom_field.pack()


        # If the value DOESNT equal "Custom"
        elif value != 'Custom':

            # Set show_field to False
            self.show_custom_field = False

            # Destroy the custom input
            self.custom_field.destroy()

            # Set up a new Entry object to pack() if we need it later.
            # Without this line, tkinter was raising an error for me.
            # This fixed it, but I don't promise that this is the
            # most efficient method to do this.
            self.custom_field = Entry(self.root)

        # If the value IS "Custom" and we're showing the custom_feild
        elif value == 'Custom' and self.show_custom_field:
            pass


        # Call this method again to keep checking the selection box
        self.root.after(100, self.check_for_selection)


app = Gui()
app.root.mainloop()

Hope this helps!希望这可以帮助!

EDIT:编辑:

To open a new window instead of packing it inside the same window as the Combobox, replace the function check_for_selection with this:要打开一个新窗口而不是将其打包在与 Combobox 相同的窗口中,请将函数check_for_selection替换为:

def check_for_selection(self):
    value = self.selections.get()

    # If the value is equal to "Custom" and show_field is set to False
    if value == 'Custom' and not self.show_custom_field:

        # Set show_field to True and pack() the custom entry field
        self.show_custom_field = True

        # Create a new window how we did when we made self.root
        self.new_window = Tk()

        # Create the Entry that will go in the window. The previous Entry widget from line 16, can be removed
        self.custom_field = Entry(self.new_window)
        self.custom_field.pack()

        # Run the new window like we did the original
        self.new_window.mainloop()


    # If the value DOESNT equal "Custom"
    elif value != 'Custom':

        # Destroy the new window that was created if it exists
        if self.show_custom_field:
            self.new_window.destroy()

        # Set show_field to False
        self.show_custom_field = False

    # If the value IS "Custom" and we're showing the custom_feild
    elif value == 'Custom' and self.show_custom_field:
        print('yes')


    # Call this method again to keep checking the selection box
    self.root.after(100, self.check_for_selection)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从 Django 的下拉列表中从用户的选定选项中进行查询 - How to make a query from a selected choice from the user from a drop-down list in Django python tk 不同的功能取决于所选的下拉列表项 - python tk different functions depending on drop down list item selected 使用 Splinter lib (Python) 选择下拉菜单中的一项 - Selecting an item of a drop-down menu with Splinter lib (Python) 使用 selenium Python 库单击下拉菜单中的项目 - Click an item in a drop-down menu using selenium Python library 蟒蛇Django。 如何在 name_znat 字段中使用下拉元素输入用户选择的文本 - Python django. How can I enter the text selected by the user with a drop-down element in the name_znat field 下拉列表选择使用 Selenium Python - Drop-down list selection using Selenium Python 在Python中使用XLwings从下拉列表中进行选择 - Pick From Drop-Down List Using XLwings in Python 带有下拉列表选择器的Python requests-html - Python requests-html with drop-down list selector 将用户输入与随机选择的列表项进行比较 - Python - Comparing user input to a randomly selected list item - Python 从下拉框中选择其他项时,更改选项卡窗口小部件的currentIndex() - Changing the currentIndex() of a tab widget when a different item is selected from a drop-down box
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM