我有一个运行while循环的程序(使用pyautogui & pysimplegui)。我希望允许用户手动取消循环/停止程序。
目前(在mac上),如果我试图以任何方式与主要的pyautogui窗口交互,我就会得到一个旋转的沙滩球。
我相信线程可能是答案,但经过大量搜索和测试,我似乎无法让它在我的代码中工作。
下面是所讨论的循环:
window=sg.Window('Meetup Auto Message', layout1, element_justification='c')
while True:
event, values = window.read()
if event in (sg.WIN_CLOSED, ' Cancel '):
break
if event == ' Ok ':
messageOptions = [values['textBox1'], values['textBox2'], values['textBox3'], values['textBox4'], values['textBox5']]
for i, (nameList, profileLink) in enumerate(zip(nameList, profileLink)):
message = "Hi " + f'{nameList}' + ", " + "\n" + f'{choice(messageOptions)}'
webbrowser.open(profileLink)
time.sleep(15)
pyautogui.press("tab")
pyautogui.write(message, interval=random.uniform(0.03, 0.15))
with pyautogui.hold("command"):
pyautogui.press("w")
window['-PROG-'].update(i+1)
if i == 10:
time.sleep(300)
window.close()
供参考全文代码:
import webbrowser
import pyautogui
import random
from random import choice
import time
import PySimpleGUI as sg
import threading
font = ("Arial", 13)
layout = [ [sg.Text('Select your .txt profiles file. Must be a list of URLs with each URL on a new line', font=("Arial", 16))],
[sg.Combo(sorted(sg.user_settings_get_entry('-filenames-', [])), default_value=sg.user_settings_get_entry('-last filename-', ''), size=(50, 1), key='-FILENAME-', font="Arial, 16"), sg.FileBrowse(font="Arial, 16"), sg.B('Clear History', font="Arial, 16")],
[sg.Button(' Ok ', bind_return_key=True, font="Arial, 16", button_color='green'), sg.Button('Cancel', font="Arial, 16")] ]
window = sg.Window('Meetup Auto Message - Profiles selection', layout)
while True:
event, values = window.read()
if event in (sg.WIN_CLOSED, 'Cancel'):
break
if event == ' Ok ':
# If OK, then need to add the filename to the list of files and also set as the last used filename
sg.user_settings_set_entry('-filenames-', list(set(sg.user_settings_get_entry('-filenames-', []) + [values['-FILENAME-'], ])))
sg.user_settings_set_entry('-last filename-', values['-FILENAME-'])
lastFile=values['-FILENAME-']
break
elif event == 'Clear History':
sg.user_settings_set_entry('-filenames-', [])
sg.user_settings_set_entry('-last filename-', '')
window['-FILENAME-'].update(values=[], value='')
window.close()
profileLink = open(lastFile).read().splitlines()
profileLink = [item.replace("+","name=") for item in profileLink]
newLinks = [item.replace("%","name=") for item in profileLink]
nameList = [i.split("name=")[1] for i in newLinks]
num_lines = sum(1 for line in open(lastFile))
BAR_MAX = num_lines
layout1 = [ [sg.Text('This program will take your messages, rotate them, add random delays and automatically message people from your profile list. You won\'t be able to use your computer while the program is running.', font="Arial, 18")],
[sg.Text('Enter your messages below just the content, we handle the "Hi Name" part.', font="Arial, 18")],
[sg.Multiline(size=(100,10), key='textBox1', font=font)],
[sg.Multiline(size=(100,10), key='textBox2', font=font)],
[sg.Multiline(size=(100,10), key='textBox3', font=font)],
[sg.Multiline(size=(100,10), key='textBox4', font=font)],
[sg.Multiline(size=(100,10), key='textBox5', font=font)],
[sg.Button(' Ok ', bind_return_key=True, font="Arial, 24", button_color='green'), sg.Button(' Cancel ', font="Arial, 24")],
[sg.Text('Progress Bar', font="Arial, 15")],
[sg.ProgressBar(BAR_MAX, orientation='h', size=(20,20), key='-PROG-')] ]
window=sg.Window('Meetup Auto Message', layout1, element_justification='c')
while True:
event, values = window.read()
if event in (sg.WIN_CLOSED, ' Cancel '):
break
if event == ' Ok ':
messageOptions = [values['textBox1'], values['textBox2'], values['textBox3'], values['textBox4'], values['textBox5']]
for i, (nameList, profileLink) in enumerate(zip(nameList, profileLink)):
message = "Hi " + f'{nameList}' + ", " + "\n" + f'{choice(messageOptions)}'
webbrowser.open(profileLink)
time.sleep(15)
pyautogui.press("tab")
pyautogui.write(message, interval=random.uniform(0.03, 0.15))
with pyautogui.hold("command"):
pyautogui.press("w")
window['-PROG-'].update(i+1)
if i == 10:
time.sleep(300)
window.close()
如果你能告诉我如何实现GUI来打破循环的话,你就能得到额外的分数!:)
编辑:我尝试过重构while循环到函数,允许我使用try:除了:关于函数.没有运气。当这样做时,我得到的值没有定义。所以我把事件,值window.open放在函数之外.试图声明全局变量等等..。这导致程序崩溃,当点击我的程序上的清除按钮时,错误是“无法读取设置文件”。
在这里不知所措。
发布于 2022-09-29 21:57:42
你被计算机科学的一个难题绊倒了。它将有“异步”、“并行执行”、“抢占”等术语。当你面对这个早期的复杂问题时,我建议你依靠尝试过的、真实的解决方案。
作弊。
如果您的示例是特定的,则只需等待几毫秒就可以查看按钮是否已按下。通常,PySimpleGui的read
将永远等待事件发生。您需要一个超时参数,特别是event, values = window.read(timeout=10)
。您还可能希望阅读这篇文章以获得更多信息。
继续编码。记笔记。
https://stackoverflow.com/questions/73898260
复制相似问题