Python Tkinter组合框 [英] Python tkinter Combobox

查看:159
本文介绍了Python Tkinter组合框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我单击组合框的名称时不填写检查之类的按钮以显示值时,我想填写我的条目。我该怎么办?

I want to fill my entries when I click in a name of my Combobox without buttons like 'check' to show the values. How can i do that?

import tkinter as tk
from tkinter import ttk
import csv

root = tk.Tk()
cb = ttk.Combobox(root,state='readonly')
labName = ttk.Label(root,text='Names: ')
labTel = ttk.Label(root,text='TelNum:')
labCity = ttk.Label(root,text='City: ')
entTel = ttk.Entry(root,state='readonly')
entCity = ttk.Entry(root,state='readonly')

with open('file.csv','r',newline='') as file:
    reader = csv.reader(file,delimiter='\t')    


cb.grid(row=0,column=1)
labName.grid(row=0,column=0)
labTel.grid(row=1,column=0)
entTel.grid(row=1,column=1)
labCity.grid(row=2,column=0)
entCity.grid(row=2,column=1)


推荐答案

您可以使用 bind()执行函数 on_select 在列表上选择元素时。

You can use bind() to execute function on_select when you select element on list.

cb.bind('<<ComboboxSelected>>', on_select)

,在此功能中,您可以填写条目

and in this function you can fill Entry.

来自GitHub的旧示例: combobox-get-selection

Old example from GitHub: combobox-get-selection

#!/usr/bin/env python3

import tkinter as tk
import tkinter.ttk as ttk

# --- functions ---

def on_select(event=None):
    print('----------------------------')

    if event: # <-- this works only with bind because `command=` doesn't send event
        print("event.widget:", event.widget.get())

    for i, x in enumerate(all_comboboxes):
        print("all_comboboxes[%d]: %s" % (i, x.get()))

# --- main ---

root = tk.Tk()

all_comboboxes = []

cb = ttk.Combobox(root, values=("1", "2", "3", "4", "5"))
cb.set("1")
cb.pack()
cb.bind('<<ComboboxSelected>>', on_select)

all_comboboxes.append(cb)

cb = ttk.Combobox(root, values=("A", "B", "C", "D", "E"))
cb.set("A")
cb.pack()
cb.bind('<<ComboboxSelected>>', on_select)

all_comboboxes.append(cb)

b = tk.Button(root, text="Show all selections", command=on_select)
b.pack()

root.mainloop()






编辑:

如果事件:< on_select 中的/ code>仅在使用 bind()时有效,因为它执行带有事件信息的功能。 command = 执行不带参数的函数,然后设置 even = None if事件: 始终为 False

Line if event: in on_select works only when you use bind() because it executes function with information about event. command= executes function without arguments and then it sets even=None and then if event: is always False.

这篇关于Python Tkinter组合框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆