Tkinter 开/关 While 循环

问题描述 投票:0回答:1

我尝试使用 Tkinter 在按下选项菜单中的“on”按钮时启动 while 循环,并在按下选项菜单中的“off”时停止 while 循环。 while 循环是无限的,但我希望我可以按“关闭”,它会退出程序。我已经使用 try: 和 KeyboardInterruption 查找了另一种方法来执行此操作,但我真的试图让它停止使用“关闭”按钮。不确定如何编码以使关闭按钮起作用,有什么建议/解决方案吗? (我是编码新手,谢谢)

import psutil, os, random, webbrowser, sys
import tkinter import*
import tkinter import tkk
import tkinter
import ttkbootstrap as tk
import keyboard


window=tk.Window()

window.title("Channel App")
window.geometry('400x300')

def Selected(event):
 if clicked.get()== 'On':
  Start_Channel()
 else:
  clicked.get() == 'Off'
 Stop_Channel()

options = [
  'On',
  'Off'
]

clicked = StringVar()
clicked.set(options[0])

drop= OptionMenu(window, clicked, *options, command= Selected)
drop.grid(row=3,column=0) 

def Stop_Channel():
 print("Stop Channel")
 sys.exit(0)

def Start_Channel():
  while True:
    vlc_found = any('vlc.exe' in proc.name() for proc in psutil.process_iter())
    print(vlc_found)

    if (vlc_found == False):
      
      print("Did not find")
      basedir=("C:\\Users\\..")

      file = random.choice([x for x in os.listdir(basedir) if os.path.isfile(os.path.join(basedir, x))])

      print("Playing file {}...".format(file))

      webbrowser.open(os.path.join(basedir, file))

     elif(Selected(event)==clicked.get()=="Off"):
         Stop_Channel()

window.mainloop()
loops tkinter button while-loop break
1个回答
0
投票

嗨,有两种解决方案,

您实际上可以放置

break
来退出 while 循环,或者您可以在
while
循环中使用条件。因为 sys.exit 将停止整个程序。从您的问题来看,我认为您需要关闭 while 循环只有,不是窗户所以,

1.突破方法

def Start_Channel():
    while True:
        vlc_found = any('vlc.exe' in proc.name() for proc in psutil.process_iter())
        print(vlc_found)

        if not vlc_found:
            print("Did not find")
            basedir = "C:\\Users\\.."
            file = random.choice([x for x in os.listdir(basedir) if os.path.isfile(os.path.join(basedir, x))])
            print("Playing file {}...".format(file))
            webbrowser.open(os.path.join(basedir, file))
        elif Selected(event) == clicked.get() == "Off":
            break

2.条件处理:

def Start_Channel():
    stop_channel = False
    while not stop_channel:
        ... #your other code
        elif Selected(event) == clicked.get() == "Off":
            stop_channel = True

警告

我只是回答您提出的问题,但说实话,您使用的方法可能会使您的应用程序完全无响应,正如

jasonharper
所说,当您在
tkinter.mainloop()
之前运行while循环时,它将阻止事件触发和更新(非响应窗口,肯定会崩溃)所以最好的方法是让你的代码使用
threading
(参考:threading Gfg)模块或使用
.after()
(参考:after方法)方法,否则你的应用程序是无法正常工作。这是因为 tkinter 就是这样工作的。您也可以使用
subrocess
模块来打开 VLC,而不是使用
webbrowser
模块(否则也可能导致错误)。

如果这个答案对您有帮助,请添加投票,以便我发表评论:)

© www.soinside.com 2019 - 2024. All rights reserved.