【问题标题】:Python tkinter ComboboxPython tkinter 组合框
【发布时间】:2017-11-26 19:43:36
【问题描述】:

我想在单击组合框的名称时填写我的条目,而没有像“检查”这样的按钮来显示值。我该怎么做?

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)

【问题讨论】:

    标签: python-3.x tkinter combobox ttk


    【解决方案1】:

    当您选择列表中的元素时,您可以使用bind() 执行函数on_select

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

    在这个函数中你可以填写Entry


    来自 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 中的行 if event: 仅在您使用 bind() 时有效,因为它执行带有事件信息的函数。 command= 执行不带参数的函数,然后设置even=None,然后if event: 始终为False

    【讨论】:

    • 我在我的代码中尝试了相同的方法,但没有成功。在“如果事件:”条件下,程序正在跳过,我使用的是相同的代码。 def on_select(event=None): print('----------------------------') if event: print("event.widget :", event.widget.get()) 只打印 '----------------'
    • 你是绑定&lt;&lt;ComboboxSelected&gt;&gt;还是在Button中使用command=bind 使用有关事件的信息执行函数 - 并且 if event 有效,但 Button 不带参数执行它,然后设置 event=None 所以 if event 为假。
    • 我的错,我使用的是 bind('>',self.on_select()) 而不是 self.on_select without () 再次感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-05
    相关资源
    最近更新 更多