简体   繁体   中英

how create an option menu in python using tkinter

how can i make option field in tkinter? For example, in html it is this:

<select>
  <option value="Option1">Option1</option>
  <option value="Option2">Option2</option>
  <option value="Option3">Option3</option>
  <option value="Option4">Option4</option>
</select>

Method 1: OptionMenu

The first method is to use OptionMenu from tkinter . You will have to create a list containing all your desired options. Then you need to have a variable that holds the information regarding which button is currently selected.

Useful resource: How can I create a dropdown menu from a List in Tkinter?

Sample code:

from tkinter import *

root = Tk()
root.geometry("300x300")

OPTIONS = [
"Option 1",
"Option 2",
"Option 3"
] #etc

variable = StringVar()
variable.set(OPTIONS[0]) # default value

w = OptionMenu(root, variable, *OPTIONS)
w.pack()

root.mainloop()

Output:

在此处输入图像描述

Method 2: Radiobutton

You can use Radiobutton in tkinter to have options.

The arguments that you need to pass in are the window which is root , the text to be displayed in the option button, a shared variable which holds the information regarding which button is currently selected , and unique value to distinguish this radio button.

Note: each radio button should have a different unique value otherwise more than one radio button will get selected.

Parameters to be passed in:

button = Radiobutton(root, text="Name on Button", variable = “shared variable”, value = “values of each button”)

Useful resources regarding Radiobutton -

  1. Radio button values in Python Tkinter
  2. https://www.geeksforgeeks.org/radiobutton-in-tkinter-python/#:~:text=The%20Radiobutton%20is%20a%20standard,calls%20that%20function%20or%20method .

Sample code:

from tkinter import *
import tkinter as tk

root = Tk()
root.geometry("300x300")

payment_method_label=Label(root, text="Select Payment Method:")

payment_method = StringVar()
payment_method.set("card")

cards = Radiobutton(root, text="Debit/Credit Card", variable=payment_method, value="card").pack(anchor=tk.W)
wallet = Radiobutton(root, text="Payment Wallet", variable=payment_method, value="wallet").pack(anchor=tk.W)
netbanking = Radiobutton(root, text="Net Banking", variable=payment_method, value="net banking").pack(anchor=tk.W)

root.mainloop()

Output:

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM