【问题标题】:Tkinter GUI is not showing, But Response is received for the functionsTkinter GUI 未显示,但功能收到响应
【发布时间】:2020-07-15 09:14:56
【问题描述】:

我正在尝试使用 tkinter 创建 GUI,目标是从 Button(Tkinter Window) 调用一个函数,没有 websocket 函数,我能够获取 Tkinter 窗口并能够通过按钮执行该函数,尝试与 Websocket 相同客户端函数,函数首先执行,Tkinter 窗口不显示。

from tkinter import *
from threading import *
import websocket
import threading
window=Tk()
window.title("Scalp")
window.geometry('400x400')
window.config(bg='lavender')


def Login():
    import requests
    import json
    global tokens

    headers = {
         'Content-Type': 'application/json',
          'Accept': 'application/json'
        }
    url = 'https://api.stocknote.com/login'
    myobj = { 'userId': 'DDXX12', 'password': 'Durant', 'yob': '1999'}

    res = requests.post(url, data = json.dumps(myobj), headers = headers)
    tokens = res.json().get("sessionToken")
    print (res.text);
    print(tokens)

def on_message(ws, msg):
        print ("Message Arrived:" + msg)
        return
def on_error(ws, error):
        print (error)
        return
def on_close(ws):
        print ("Connection Closed")
        return
def on_open(ws):
        print ("Sending json")
        data='{"request":{"streaming_type":"quote", "data":{"symbols":[{"symbol":"45402_NFO"}]}, "request_type":"subscribe", "response_format":"json"}}'
        ws.send(data)
        ws.send("\n")
        return
def connection():
        Login()
        headers = {'x-session-token': tokens }
        websocket.enableTrace(True)
        ws = websocket.WebSocketApp("wss://stream.stocknote.com", on_open = on_open, on_message = on_message, on_error = on_error, on_close = on_close, header = headers)
        ws.run_forever()
        return
a=Button(window,text='Login',width=12,bg='azure',command=Login(),fg='black',font('bold',14),activebackground='dark sea green',activeforeground='khaki3')
a.place(x=100,y=50)
b=Button(window,text='BankNifty',width=12,bg='azure',command=connection(),fg='black',font('bold',14),activebackground='dark sea green',activeforeground='khaki3')
b.place(x=100,y=90)
window.mainloop

没有出现Tkinter窗口,而是直接执行函数。

【问题讨论】:

  • 是复制粘贴错误还是最后一行缺少括号?应该是window.mainloop(),否则该行将无济于事。
  • @Lenormju 即使没有括号它的工作。尝试使用 tkinter 进行相同操作时,GUI 未显示。
  • stackoverflow.com/q/5767228/7432。还有,为什么要导入两次threading,却不使用呢?

标签: python python-3.x tkinter websocket


【解决方案1】:

你的代码有几个问题。

首先,你没有打电话给mainloop。您需要将window.mainloop 更改为window.mainloop()

第二个问题是您在启动时立即调用connectionLogin,因为您指定错误。

创建按钮时,您必须传递一个可调用对象。在您的情况下,您会立即调用该函数,然后将结果传递给 command 选项。您需要将command=Login() 更改为command=Login,并将command=connection() 更改为command=connection

最后,当connection 被调用时,它会调用 ws.run_forever()。这是一个阻塞调用——它不会返回。因为它没有返回,所以 tkinter 事件循环(以mainloop() 开始)永远没有机会运行。因为它不运行,所以它甚至不能处理基本事件,比如显示窗口的请求。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-29
    • 1970-01-01
    • 2013-06-04
    • 2019-04-23
    • 1970-01-01
    相关资源
    最近更新 更多