【问题标题】:Exit when checkbox is ticked, if not, don't exit script (tkinter, python)勾选复选框时退出,如果没有,不要退出脚本(tkinter,python)
【发布时间】:2022-10-23 00:48:36
【问题描述】:

我正在为我的 python 脚本制作一个 tkinter 应用程序。我想确保当用户勾选“自动退出”复选框时,脚本将在完成后自动退出 - 关闭 gui 应用程序。

但是如果用户这样做不是勾选此框,则脚本将照常停止,但 gui 应用程序将保持打开状态。我正在为 gui 使用开源基础,因为我认为它看起来不错。这主要仅用于个人使用和实验目的。

我怎样才能做到这一点?谢谢。

代码:

import tkinter
import customtkinter
import webbrowser
import pyautogui

def main_script():
    webbrowser.open('https://www.google.com')
    pyautogui.moveTo(500, 500)
# this is where I want the script to stop, but the gui app remaining open if checkbox is ticked. 
# If not, then everything will close.

self.check_box_1 = customtkinter.CTkCheckBox(master=self.frame_right,
                                                     text="Auto exit")
        self.check_box_1.grid(row=2, column=2, pady=20, padx=40, sticky="w")

【问题讨论】:

  • 只需调用self.check_box_1.get() 来检查复选框是否在main_script() 中被选中,然后根据结果做任何你想做的事情。

标签: python python-3.x tkinter pyautogui customtkinter


【解决方案1】:

您可以使用设置变量的命令,然后在main_script 末尾检查该变量。

auto_exit = False
auto_exit_var = tkinter.IntVar()

def main_script():
    webbrowser.open('https://www.google.com')
    pyautogui.moveTo(500, 500)
    if auto_exit:
        root.destroy() # Replace root with your window name

def toggle_auto_exit():
    global auto_exit
    auto_exit = auto_exit_var.get() == 1


self.check_box_1 = customtkinter.CTkCheckBox(master=self.frame_right, text="Auto exit", variable = auto_exit_var, command = toggle_auto_exit)
self.check_box_1.grid(row=2, column=2, pady=20, padx=40, sticky="w")

我添加了两个全局变量auto_exitauto_exit_varauto_exit_var 是一个跟踪复选框值的 Tkinter IntVar。当复选框被按下时,它调用toggle_auto_exit,它获取IntVar 的值并将其与1(打开)进行比较并将其存储在auto_exit 中。

看起来您已经在使用一个类,因此可以避免使用全局变量。我使用 Tkinter Checkbutton 对此进行了测试,所以我不确定自定义 Tkinter 小部件是否可以正常工作,但应该可以。

【讨论】:

  • 感谢您的回复,我已将此添加到我的代码中,但是它不会关闭应用程序。有什么可能妨碍我的情况吗?
  • 没有更多的上下文很难说。如果您可以提供minimal reproducible example 作为对您问题的编辑,那将很有用。
猜你喜欢
  • 2014-03-24
  • 1970-01-01
  • 2019-07-05
  • 2012-12-21
  • 2017-12-03
  • 1970-01-01
  • 2020-10-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多