如何一起运行两个阻塞循环-Tkinter和Discord

时间:2019-06-02 00:08:45

标签: python tkinter discord.py

我想运行discord.py,它是Discord API的包装器,可帮助构建基于python的机器人。我想运行tkinter来允许机器人的某些外部接口(例如开始和停止按钮)。

如果我先运行tkinter,则启动机器人后GUI会锁定。如果我先运行该机器人,则GUI无法启动。我还不了解该问题,但我认为它们都在运行阻塞循环。我认为多线程和睡眠是解决此问题的方法。

import discord
import tkinter
bot = discord.Client()
root = tkinter.Tk()

# Methods without arguments to be called from buttons
def start():
    with open('token.txt') as f:
        TOKEN = f.readline()
    bot.run(TOKEN)
def stop():
    bot.close()

# This is how discord.py uses messages
@bot.event
async def on_message(message):
    if message.content == 'ping':
        await message.channel.send('pong')

if __name__ == '__main__':
    # Building a GUI
    canvas = tkinter.Canvas(root, height=300, width=400, bd=5)
    canvas.pack()
    frame = tkinter.Frame(root, bd=5)
    frame.place(relx=0.05, rely=0.05, relwidth=.9, relheight=.9)

    btn_start = tkinter.Button(frame, text="Start", command=start)
    btn_start.place(relx=0.25, rely=.4, relheight=.2, relwidth=0.25)
    btn_stop = tkinter.Button(frame, text="Stop", command=stop)
    btn_stop.place(relx=0.5, rely=.4, relheight=.2, relwidth=0.25)

    # Here's the juicy code bits that we've come for:
    root.mainloop()

0 个答案:

没有答案