我是python新手,来自Java,我想更新初始化类中的一个变量
这是我的完整代码
import datetime import time import threading
from tkinter import * from ibapi.client import EClient, TickAttribBidAsk from ibapi.wrapper import EWrapper, TickTypeEnum from ibapi.contract import Contract
class TestApp(EWrapper, EClient):
def __init__(self):
EClient.__init__(self, self)
def tickPrice(self, reqId, tickType, price, attrib):
print("Tick price. Ticker Id:", reqId, "tickType:", TickTypeEnum.to_str(tickType), "Price:", price, end=' ')
def tickByTickBidAsk(self, reqId: int, time: int, bidPrice: float, askPrice: float, bidSize: int, askSize: int, tickAttribBidAsk: TickAttribBidAsk):
print(bidPrice)
tkinterApp.price1 = bidPrice
class Application:
def runTest(self):
app = TestApp()
app.connect("127.0.0.1", 7497, 0)
contract = Contract()
contract.symbol = "PROG"
contract.secType = "STK"
contract.currency = "USD"
contract.exchange = "SMART"
contract.primaryExchange = "NASDAQ"
time.sleep(1)
app.reqMarketDataType(1)
app.reqTickByTickData(19003, contract, "BidAsk", 0, True)
app.run()
def __init__(self):
t = threading.Thread(target=self.runTest)
t.start()
self.runTest()
class TkinterClass:
ibkrConnection = Application()
root = Tk()
root.title("test")
root.grid_columnconfigure((0, 1), weight=1)
titleTicker = Label(root, text="TICKER", bg='black', fg='white', width=100)
titleRating = Label(root, text="PRICE", bg='black', fg='white', width=100)
ticker1 = Label(root, text="PROG", bg='black', fg='white', width=100)
price1 = Label(root, text=0, bg='black', fg='white', width=100) # To be changed with every tick
titleTicker.grid(row=1, column=1)
titleRating.grid(row=1, column=2)
ticker1.grid(row=2, column=1)
price1.grid(row=2, column=2)
root.mainloop()
tkinterApp = TkinterClass()
deftickByTickBidAsk
是一个回调函数,每隔2秒调用一次
我想更新类TkinterClass
中的price1
变量,但是当我尝试执行代码时,tkinterApp.price1 = bidPrice
行给了我一个名称错误:TkinterClass is not defined
我知道这可能是个错误:)
如果您这样做可能会有所帮助:
但是,仍然存在一些问题:
tkinterApp.price1
{要设置标签,请使用:}存储
tkinterApp.price1.config(str(value))
或使用tkinter
{price1
文本,并使用该StringVar
作为Label
值tkinterApp.price1
变量如果您在后台线程中乱搞Tk变量,Tk可能会不高兴。我建议在前台线程中运行某种计时器,并轮询在后台更新的变量,因此您只能从前台更新Tk变量
使用
root.after(ms, callback)
在前台计划回调(在调用root.mainloop()
之前)我不认为在读取另一个线程中更新的Python值时需要
threading.Lock
,但是在更新和访问逻辑周围添加lock()/unlock()
会更安全几年前我玩过tk,这就是我构建代码的方式。我创建了一个tkinter窗口,并从tkinter类连接到TWS
相关问题 更多 >
编程相关推荐