更改变量时,Tkinter Checkbutton不更新 [英] Tkinter Checkbutton not updating when changing variable

查看:207
本文介绍了更改变量时,Tkinter Checkbutton不更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个正在使用的Macbook上的python 3.8中的tkinter GUI.我遇到了一个问题,即更改与复选按钮关联的变量不会更改复选按钮本身的外观.如果我将与其关联的IntVar()设置为1,我希望该复选按钮显示为选中状态,并且从我阅读的所有内容来看,这种情况应该会发生.

下面是一些非常简化的代码来显示问题:

import tkinter as tk

class Window():
    def __init__(self, master):
        var = tk.IntVar()
        checkbutton = tk.Checkbutton(master, variable=var)
        checkbutton.pack()
        var.set(1)

root = tk.Tk()
Window(root)
root.mainloop()

运行脚本时,未选中复选按钮.我仍然可以通过单击检查按钮.这是一个已知的错误还是我错过了什么?

解决方案

已解决:正如jasonharper所指出的那样,问题是垃圾收集. tkinter变量没有被用于任何东西,而只是作为局部变量存储,因此它被扔掉了,并且不能被checkbutton引用.将IntVar保存在某个卡住的位置可以解决此问题.一种解决方案是将变量保存在检查按钮本身的var属性中:

import tkinter as tk

class Window():
    def __init__(self, master):
        var = tk.IntVar()
        checkbutton = tk.Checkbutton(master, variable=var)
        checkbutton.pack()
        var.set(1)
        checkbutton.var = var

root = tk.Tk()
Window(root)
root.mainloop()

I have a tkinter GUI that I'm working on in Python 3.8 on my Macbook. I've encountered a problem where changing the variable associated with a checkbutton doesn't change the appearance of the checkbutton itself. I'd like the checkbutton to show up as checked if I set the IntVar() associated with it to 1, and from everything I've read, this should be happening.

Here's some extremely simplified code showing the problem:

import tkinter as tk

class Window():
    def __init__(self, master):
        var = tk.IntVar()
        checkbutton = tk.Checkbutton(master, variable=var)
        checkbutton.pack()
        var.set(1)

root = tk.Tk()
Window(root)
root.mainloop()

When I run the script, the checkbutton isn't checked. I am still able to check the checkbutton by clicking on it though. Is this a known bug or am I missing something?

解决方案

Solved: The issue, as jasonharper pointed out, was garbage collection. The tkinter variable wasn't being used for anything and was just being stored as a local variable, so it was thrown out and couldn't be referenced by the checkbutton. Saving the IntVar somewhere that stuck around fixed the problem. One solution was saving the variable in the var attribute of the checkbutton itself:

import tkinter as tk

class Window():
    def __init__(self, master):
        var = tk.IntVar()
        checkbutton = tk.Checkbutton(master, variable=var)
        checkbutton.pack()
        var.set(1)
        checkbutton.var = var

root = tk.Tk()
Window(root)
root.mainloop()

这篇关于更改变量时,Tkinter Checkbutton不更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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