【问题标题】:When using tkinter in python, how to call a checkbox which is in a fuction in another function?在python中使用tkinter时,如何在另一个函数中调用一个函数中的复选框?
【发布时间】:2016-07-12 03:19:47
【问题描述】:

例如我在一个.py文件中有如下代码:

import tkinter
def main():
    top = tkinter.Tk()
    top.title("Main")

    Var = tkinter.IntVar()
    CheckBox = tkinter.Checkbutton(top, text="test", variable=Var)
    CheckBox.grid(column=1, row=1)

    startButton = tkinter.Button(top, text="Start", command=lambda: a(Var))
    startButton.grid(column=1, row=2)

    top.mainloop()

def a(Var):
    print(Var.get())

在另一个 b.py 文件中我有以下代码

import a
import tkinter

top = tkinter.Tk()
top.title("Test")

def run():
    a.main()

startButton = tkinter.Button(top, text="Start", command=run)
startButton.grid(column=0, row=0)

top.mainloop()

我期望的是,当我选中复选框时,它将打印 1,如果取消选中它将打印 0。 但是,无论我选中还是取消选中复选框,它都会打印 0。我怎样才能使复选框起作用?

【问题讨论】:

    标签: python checkbox tkinter


    【解决方案1】:

    这是因为您有两个 Tk 实例。 Tkinter 被设计为一次只有一个实例。每个实例都有自己的内部命名空间,因此一个实例中的变量对另一个实例是不可见的。

    【讨论】:

      【解决方案2】:

      Vara.py 的本地地址,因此您必须找到使其可供b.py 访问。简单的import a 是不够的,除非你在 a.py 中这样定义 Var:

      a.py

      import tkinter
      
      # Must be done here otherwise we can not declare Var above
      top = tkinter.Tk() 
      # Make Var available to b.py
      Var = tkinter.IntVar()
      
      def main():
          global Var
          global top
      
          #top = tkinter.Tk()
          top.title("Fix Ratio")
      
          Var = tkinter.IntVar()
          CheckBox = tkinter.Checkbutton(top, text="test", variable=Var)
          CheckBox.grid(column=1, row=1)
      
          startButton = tkinter.Button(top, text="Start", command=lambda: a(Var))
          startButton.grid(column=1, row=2)
      
          #top.mainloop()
      
      def a(Var):
          print(Var.get())
      

      b.py

      如果您想在实际运行的程序中显示 2 个单独的窗口,则需要将 top 重命名为 b.py 中的其他名称:

      import tkinter
      import a # Var now is accessible from b.py
      
      to = tkinter.Tk()
      to.title("Conditioning")
      
      def run():
          a.main()
      
      startButton = program.tkinter.Button(to, text="Start", command=run)
      startButton.grid(column=0, row=0)
      
      to.mainloop()
      

      演示:

      这是在取消选中检查按钮并随后选中时运行上述程序的 b.py 屏幕截图:

      【讨论】:

      • 它可以工作,但是在按下第一个窗口上的开始按钮之前会出现第二个 tkinter 窗口。在第一个窗口上按下开始按钮然后第二个窗口出现而不是让它首先出现然后更新它之后,是否可以让它工作?因为在控制更多窗口时,让它们首先出现并不是那么好。谢谢
      • 顺便说一句,在我自己的程序中,我也在与复选框相同的功能中使用 tkinter.Entry,但它工作正常。我不知道为什么它可以正常工作,但复选框不能。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多