tkinter中的跟踪方法

时间:2017-09-07 01:52:35

标签: python tkinter combobox

我希望Combobox 2根据1个Combobox的状态显示不同的值。 Combobox 2还会更改Entry框的状态。我不明白为什么on_field_change函数没有问题,但check_website给我一个TypeError: trace_variable() missing 1 required positional argument: 'callback'错误。为什么?有什么建议吗?

import tkinter as tk
from tkinter import ttk


main = tk.Tk()
app = tk.Frame(main)
app.grid()


def on_field_change(index, value, op):
    if novel.get() in has_book_website1:
        book_number_chosen.configure(state="enabled")
    else:
        book_number_chosen.configure(state="disabled")


def check_website(index, value, op):
    if website.get() == "Website1":
        novel_chosen["values"] = namelist_website1
    elif website.get() == "Website2":
        novel_chosen["values"] = namelist_website2


website = tk.StringVar
website_chosen = ttk.Combobox(app, width=42, textvariable=website,                         
                 state="readonly")
website.trace("w", check_website)
website_chosen["values"] = ["Website1", "Website12"]
website_chosen.current(0)
website_chosen.grid(column=1, row=0)

book_number = tk.IntVar()
book_number_chosen = ttk.Entry(app, width=5, textvariable=book_number,             
state="disabled")


novel = tk.StringVar()
novel_chosen = ttk.Combobox(app, width=42, textvariable=novel, 
               state="readonly")
novel.trace("w", on_field_change)
novel_chosen["values"] = ["1", "2"]
novel_chosen.grid(column=1, row=1)
novel_chosen.current(0)

has_book_website1 = ["2"]

namelist_website1 = ["Just", "some", "text"]
namelist_website2 = ["lorem", "ipsum"]

main.mainloop()

1 个答案:

答案 0 :(得分:2)

这只是因为你写了website = tk.StringVar而不是website = tk.StringVar()

为什么会导致此错误?

您将website变量分配给tk.StringVar ,而实际上是要将其分配给它的实例(由带括号的电话)。 tk.StringVar.trace方法或多或少地定义如下:

class StringVar(...):
    ...
    def trace(self, mode, callback):
        ...

由于website指向website.trace指的是类方法。 因此,当您致电website.trace("w", check_website)时,"w"将作为self传递,check_website将作为mode传递,并且该调用缺少参数。

另一方面,如果website被定义为tk.StringVar实例,则website.trace会引用实例方法website隐式传递为self

附上那些括号,你很好。