【问题标题】:Python, combobox does not modify elements with IFPython,组合框不使用 IF 修改元素
【发布时间】:2021-06-10 04:40:12
【问题描述】:

我开始使用 Python 中的 Tkinter。我很难做一件简单的事情。有两个组合框。例如,在第一个组合框Category中选择文本“”Test1“,我想在第二个combobox Subcategory中打开Hello1”、“Hello2”、“Hello3”。

也许我一开始就写错了代码。我想问你两件事:

  1. 你能帮我解决我的 IF 问题吗?

  2. 我认为我没有从第一行编写正确的代码。你能给我一个所有代码的系统吗?幸好时间不长谢谢

     from tkinter import *
     from tkinter import ttk
     import sqlite3
    
     window=Tk()
     window.title("aaaa")
     window.geometry("700x700")
    
     categoria=["Test1", "Test2", "Test3"]
     categoria=ttk.Combobox(window,value=categoria,width=16)
     categoria.place(x=5, y=100)
     categoria.set("Scegliere categoria")
     categoria.pack
    
     sottocategoria=["aaaa"]
     sottocategoria=ttk.Combobox(window,value=sottocategoria,width=16)
     sottocategoria.place(x=5, y=130)
     sottocategoria.pack
    
     if categoria == ("Test1"):
     sottocategoria = ["Hello1", "Hello2", "Hello3"]
    
    
     window.mainloop()
    

【问题讨论】:

标签: tkinter


【解决方案1】:

您需要跟踪变量。您基本上是在进行过程编程,python 从上到下读取。但是,当您分配该值并将其转到if 语句时,该值的计算结果为 False。然后mainloop 只是显示窗口的循环。此外,您可以使用StringVar() 获取值并检测任何更改。

from tkinter import *
from tkinter import ttk

window=Tk()
cat=StringVar()
sub_cat=StringVar()
def change_val(*args):
    if cat.get() == "Test1":
        sottocategorias = ["Hello1", "Hello2", "Hello3"]
        sottocategoria.config(values=sottocategorias)
    else:
        sottocategorias = ["aaaa"]
        sottocategoria.config(values=sottocategorias)
window.title("aaaa")
window.geometry("700x700")
categorias=["Test1", "Test2", "Test3"]
categoria=ttk.Combobox(window,value=categorias,textvariable=cat,width=16)
categoria.place(x=5, y=100)
cat.set("Scegliere categoria")
sottocategorias=["aaaa"]
sottocategoria=ttk.Combobox(window,textvariable=sub_cat,value=sottocategorias,width=16)
sottocategoria.place(x=5, y=130)


cat.trace("w",change_val)
window.mainloop()

【讨论】:

  • 有一个虚拟事件<<ComboboxSelected>>,您可以使用它来代替trace
  • 好的@CoolCloud,我没有意识到这一点。谢谢
  • 为什么在上面使用place后会有categoria.pack?我尝试复制粘贴代码,但它不符合 OP 的要求。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-16
  • 2013-01-21
  • 1970-01-01
  • 1970-01-01
  • 2018-02-18
  • 1970-01-01
  • 2011-11-10
相关资源
最近更新 更多