在Tkinter中勾选复选框没有效果。

huangapple go评论63阅读模式
英文:

checking a checkbox has no effect in Tkinter

问题

以下是您提供的代码的翻译部分:

在一个框架内我已经添加了复选框但是选中它们对复选框变量没有影响这段代码可能有什么问题

def set_insider_trades():

    def on_mousewheel(event):
        canvas.yview_scroll(int(-1 * (event.delta / 120)), "units")

    set_inside_trading = tk.Tk()
    set_inside_trading.title("设置内幕交易")
    set_inside_trading.geometry("300x600")

    # 向画布添加滚动条
    scrollbar = ttk.Scrollbar(set_inside_trading, orient=tk.VERTICAL)
    scrollbar.pack(side=tk.RIGHT, fill=tk.Y)

    # 创建画布
    canvas = tk.Canvas(set_inside_trading, borderwidth=0, yscrollcommand=scrollbar.set)
    canvas.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)

    # 配置滚动条以滚动画布
    scrollbar.config(command=canvas.yview)

    # 在画布内创建一个框架
    frame = tk.Frame(canvas)

    # 将框架添加到画布中
    canvas.create_window((0, 0), window=frame, anchor=tk.NW)

    # 配置画布滚动区域
    frame.bind("<Configure>", lambda event: canvas.configure(scrollregion=canvas.bbox("all")))

    # 绑定鼠标滚轮事件以滚动
    frame.bind_all("<MouseWheel>", on_mousewheel)

    # 为每个公司创建复选框
    checkbox_vars = {company: tk.BooleanVar(value=False) for company in df.index}
    for idx, (company, var) in enumerate(checkbox_vars.items()):
        checkbox = tk.Checkbutton(frame, text=company, variable=var)
        checkbox.grid(row=idx, column=0, sticky="w", padx=(10, 0), pady=5)

    def update_companies():
        for company, var in checkbox_vars.items():
            if var.get():
                df.loc[company, '上季度内部交易购买'] = 1
            else:
                df.loc[company, '上季度内部交易购买'] = 0

    ok_button = tk.Button(set_inside_trading, text="确定", command=lambda: [update_companies(), set_inside_trading.destroy()])
    ok_button.place(relx=0.5, rely=1.0, anchor=tk.S)

希望这有助于理解代码的翻译部分。如果您有任何其他问题,请随时提出。

英文:

Inside a frame, I have populated checkboxes. But checking them has no effect on the checkbox_vars. what could be wrong with this piece of code?

def set_insider_trades():
def on_mousewheel(event):
canvas.yview_scroll(int(-1 * (event.delta / 120)), &quot;units&quot;)
set_inside_trading = tk.Tk()
set_inside_trading.title(&quot;Set Insider Trading&quot;)
set_inside_trading.geometry(&quot;300x600&quot;)
# Add a Scrollbar to the Canvas
scrollbar = ttk.Scrollbar(set_inside_trading, orient=tk.VERTICAL)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
# Create a Canvas
canvas = tk.Canvas(set_inside_trading, borderwidth=0, yscrollcommand=scrollbar.set)
canvas.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
# Configure the scrollbar to scroll the canvas
scrollbar.config(command=canvas.yview)
# Create a Frame within the Canvas
frame = tk.Frame(canvas)
# Add the Frame to the Canvas
canvas.create_window((0, 0), window=frame, anchor=tk.NW)
# Configure the Canvas Scroll Region
frame.bind(&quot;&lt;Configure&gt;&quot;, lambda event: canvas.configure(scrollregion=canvas.bbox(&quot;all&quot;)))
# Bind Mousewheel Event to Scroll
frame.bind_all(&quot;&lt;MouseWheel&gt;&quot;, on_mousewheel)
# Create checkboxes for each company
checkbox_vars = {company: tk.BooleanVar(value=False) for company in df.index}
for idx, (company, var) in enumerate(checkbox_vars.items()):
checkbox = tk.Checkbutton(frame, text=company, variable=var)
checkbox.grid(row=idx, column=0, sticky=&quot;w&quot;, padx=(10, 0), pady=5)
def update_companies():
for company, var in checkbox_vars.items():
if var.get():
df.loc[company, &#39;Insider &amp; SAST Buys Last Quarter&#39;] = 1
else:
df.loc[company, &#39;Insider &amp; SAST Buys Last Quarter&#39;] = 0
ok_button = tk.Button(set_inside_trading, text=&quot;OK&quot;, command=lambda: [update_companies(), set_inside_trading.destroy()])
ok_button.place(relx=0.5, rely=1.0, anchor=tk.S)

答案1

得分: 1

尝试使用回调函数进行一些调试。我发现复选框状态未按预期更新。这通常发生在创建新的 Tkinter 实例(Tk() 或 Toplevel())时,而另一个实例仍在运行,导致意外行为,因为两个实例之间存在冲突。

set_insider_trades() 创建了一个新的 Tk() 窗口。我将其更改为 Toplevel(),然后它正常工作。

在 Tkinter 中,应该只有一个 Tk() 实例,作为主应用程序窗口。任何附加窗口都应该是 Toplevel() 的实例。这是问题的根本原因。

英文:

tried some debugging using callback function. I found that the checkbox state is not being updated as expected. This usually happens when a new Tkinter instance (Tk() or Toplevel()) is created while another one is still running, causing unexpected behavior due to conflicts between the two instances.

set_insider_trades() creates a new Tk() window. I changed it to Toplevel() and it worked fine.

In Tkinter, there should only be one Tk() instance, which serves as the main application window. Any additional windows should be instances of Toplevel(). This was the root of the problem.

huangapple
  • 本文由 发表于 2023年5月13日 18:54:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/76242348.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定