Checkbutton和Scale冲突

时间:2016-10-09 13:16:37

标签: python tkinter

我的Checkbutton小部件有问题。每次我选择它时,上面的缩放小部件上的滑块自身移动到1,取消选择Checkbutton小部件会将Scale小部件设置为0.两个小部件不会以任何方式相互关联,因为某些原因更改值其中一个影响另一个。任何人都可以向我解释为什么会发生这种情况,以及如何在将来避免这些问题?

    tk.Label(f7, text=("Jakość")).grid(row=3, column=0)
    self.jakosc=tk.Scale(f7, orient='horizontal', variable=jakosc)
    self.jakosc.grid(row=3, column=1)
    self.rozpinany_sweter=tk.IntVar()
    tk.Checkbutton(f7, text='Rozpinany',variable=rozpinany_sweter).grid(row=4, column=1)

In this example  检查滑块上的复选框后,滑块设置为56,将其自身设置为1。

编辑:MCVE提供:

import tkinter as tk
from tkinter import ttk as ttk
RS=0
Q=0
class Aplikacja(tk.Frame):
def __init__(self, *args, **kwargs):
    tk.Frame.__init__(self, *args, **kwargs)
    self.grid()
    self.create_widgets()
def create_widgets(self):
    self.jakosc=tk.Scale(root, orient='horizontal', variable=Q)
    self.jakosc.grid()
    self.rozpinany_sweter=tk.IntVar()
    tk.Checkbutton(root, variable=RS).grid()

root= tk.Tk()
app= Aplikacja(root)
root.mainloop()

1 个答案:

答案 0 :(得分:0)

The variable= parameter to Tk widgets MUST be a Tk variable (created by Tk.IntVar() or similar calls). Your code passes Q and RS, which are ordinary Python variables; the one Tk variable you create is pointless, because you never use it anywhere. Tk variables have a special ability not possessed by Python variables: they can have watchers attached to them, which allows widgets to automatically update themselves when the variable is modified.

The Python representation of a Tk variable is basically just the Tk name of the variable. Both Q and RS happen to have the same value, so they're both referring to the same variable on the Tk side - that's why your scale and checkbox appear to be linked.