杰瑞科技汇

Python dropdownlist如何实现与交互?

Of course! A "dropdown list" in Python is most commonly implemented using a combo box or choice widget from a GUI library. The most popular library for this is Tkinter, which comes built-in with Python.

Python dropdownlist如何实现与交互?-图1
(图片来源网络,侵删)

I'll show you how to create dropdown lists using three different libraries, from the simplest (Tkinter) to the more powerful and modern (PyQt/PySide) and web-based (Streamlit).


Using Tkinter (Built-in, Simple & Great for Beginners)

Tkinter is the standard GUI library for Python. Its dropdown widget is called ttk.Combobox.

Basic Example

This example creates a window with a label, a dropdown list, and a button. When you click the button, it prints the currently selected item.

import tkinter as tk
from tkinter import ttk
# --- Create the main window ---
root = tk.Tk()"Tkinter Dropdown List")
root.geometry("300x150")
# --- Define the options for the dropdown ---
options = ["Option 1", "Option 2", "Option 3", "Option 4"]
# --- Create a StringVar to track the selection ---
# This is a special Tkinter variable that updates automatically
selected_option = tk.StringVar()
# --- Create the dropdown (Combobox) ---
# The 'textvariable' links the dropdown to our StringVar
# The 'values' are the options we defined
dropdown = ttk.Combobox(root, textvariable=selected_option, values=options, state="readonly")
# --- Position the dropdown in the window ---
# .pack() is a simple geometry manager
dropdown.pack(pady=20, padx=20, fill='x')
dropdown.current(0) # Set a default selection (index 0)
# --- Create a button to trigger an action ---
def on_button_click():
    # Get the current value from the StringVar
    choice = selected_option.get()
    print(f"You selected: {choice}")
    # You can also access the widget directly: dropdown.get()
button = ttk.Button(root, text="Get Selection", command=on_button_click)
button.pack(pady=10)
# --- Start the event loop ---
root.mainloop()

Explanation of Key ttk.Combobox Arguments:

  • root: The parent window.
  • textvariable: A Tkinter StringVar that holds the current value of the dropdown. This is the best way to track the selection.
  • values: A tuple or list of strings to be displayed in the dropdown.
  • state:
    • 'readonly': The user can select from the list but cannot type in it. This is the standard behavior for a dropdown.
    • 'normal': The user can both select from the list and type a new value.
    • 'disabled': The dropdown is completely unresponsive.

Using PyQt6 / PySide6 (Modern & Powerful)

PyQt and PySide are feature-rich libraries for creating professional desktop applications. They use a signal-and-slot mechanism for handling events.

Python dropdownlist如何实现与交互?-图2
(图片来源网络,侵删)

Basic Example with PyQt6

First, you need to install the library: pip install PyQt6

import sys
from PyQt6.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QWidget, QLabel, QComboBox, QPushButton
class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("PyQt6 Dropdown List")
        self.setGeometry(300, 300, 300, 200)
        # Create a central widget and a layout
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        layout = QVBoxLayout(central_widget)
        # --- Define the options ---
        options = ["Option A", "Option B", "Option C", "Option D"]
        # --- Create the dropdown (QComboBox) ---
        self.dropdown = QComboBox()
        self.dropdown.addItems(options)
        self.dropdown.setCurrentIndex(0) # Set a default selection
        # --- Create a label to show the selection ---
        self.selection_label = QLabel("Current Selection: ")
        # --- Create a button ---
        button = QPushButton("Get Selection")
        # --- Connect the button's 'clicked' signal to our method ---
        button.clicked.connect(self.on_button_click)
        # --- Add widgets to the layout ---
        layout.addWidget(self.dropdown)
        layout.addWidget(self.selection_label)
        layout.addWidget(button)
    def on_button_click(self):
        # Get the current text from the dropdown
        current_text = self.dropdown.currentText()
        self.selection_label.setText(f"Current Selection: {current_text}")
        print(f"You selected: {current_text}")
# --- Standard boilerplate to run the app ---
if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec())

Explanation of Key QComboBox Methods:

  • addItems(items): Adds a list of strings to the dropdown.
  • setCurrentText(text) or setCurrentIndex(index): Sets the default selection.
  • currentText(): Returns the currently selected item's text.
  • currentIndex(): Returns the index of the currently selected item.

Using Streamlit (For Web Apps & Data Science Dashboards)

Streamlit is a fantastic library for creating web apps for machine learning and data science with minimal code. It has a built-in st.selectbox function.

First, install Streamlit: pip install streamlit

Basic Example

Create a Python file (e.g., app.py) and run it with streamlit run app.py.

Python dropdownlist如何实现与交互?-图3
(图片来源网络,侵删)
import streamlit as st
"Streamlit Dropdown List")
# --- Define the options ---
options = ["Data Analysis", "Machine Learning", "Deep Learning", "Computer Vision"]
# --- Create the dropdown (st.selectbox) ---
# The first argument is the label shown to the user.
# The second is the list of options.
# The 'key' is optional but useful for referencing the widget later.
selected_option = st.selectbox(
    "Choose a topic:",
    options,
    key="topic_selector"
)
# --- Display the selection ---
# Streamlit automatically re-runs the script when a selection is made.
st.write(f"You selected: **{selected_option}**")
# You can use the selection in conditional logic
if selected_option == "Machine Learning":
    st.write("Great choice! Here are some resources...")
    st.markdown("[Scikit-learn Documentation](https://scikit-learn.org/stable/)")
elif selected_option == "Data Analysis":
    st.write("Pandas and NumPy are your friends!")
    st.markdown("[Pandas Documentation](https://pandas.pydata.org/docs/)")

Explanation of st.selectbox:

  • The first argument is the widget's label.
  • The second argument is the list of options.
  • The function returns the currently selected value. This value is available for the rest of your script.
  • Streamlit handles all the web backend and interactivity for you.

Summary & Recommendation

Library Best For Ease of Use Key Widget Installation
Tkinter Simple desktop apps, beginners, scripts Very Easy ttk.Combobox Built-in (pip install tkinter)
PyQt6/PySide6 Professional, complex desktop apps Moderate QComboBox pip install PyQt6 or pip install PySide6
Streamlit Web apps, data dashboards, ML demos Very Easy st.selectbox pip install streamlit
  • For quick scripts and simple tools, use Tkinter.
  • For building full-featured desktop applications, use PyQt6 or PySide6.
  • For creating shareable web apps and data science projects, use Streamlit.
分享:
扫描分享到社交APP
上一篇
下一篇