所以我正在创建一个自动收录器,它会在屏幕顶部显示新闻标题。在抓取之后,我将所有标题转换为单行字符串(大约8000个字符),以便通过自动收录器(带有文本+移动的tkinter画布)连续滚动它。
然而,在文本的中途,它只是停止移动。之后的文字仍然没有显示。检查完txt后。文件字符串来自,它停止的地方没有什么特别之处。没有换行符,制表符或特殊字符。那是什么让我认为它与单行文本太长而无法显示...我还增加了画布高度,看它是否正在进行任何类型的包装,将文本留在下面的行中,但事实并非如此。希望有人会知道这是什么。感谢。
代码:
import time
import os
import re
try:
# Python2
import Tkinter as tk
except ImportError:
# Python3
import tkinter as tk
#Create Root Object-----------------------------------------------------------
root = tk.Tk()
canvas = tk.Canvas(root, height=25, width=root.winfo_screenwidth()-180, bg="black", highlightthickness=0, relief='ridge')
canvas.pack()
root.overrideredirect(1)
root.wm_attributes("-topmost", 1)
script_dir = os.path.dirname(os.path.abspath(__file__))
dat="todisplay.txt"
pathy = os.path.join(script_dir, dat)
f = open(pathy, 'r')
lines = f.readlines()
mystr = '\t'.join([line.strip() for line in lines])
mystr = re.sub( '\s+', ' ', mystr ).strip()
x = 0
y = 0
text = canvas.create_text(x, y, anchor='nw', text=mystr, font=('Helvetica',11), fill='orange')
dx = 1
dy = 0
while True:
canvas.move(text, -dx, dy)
canvas.config(scrollregion=canvas.bbox('all'))
canvas.update()
time.sleep(.001)
root.mainloop()
出于测试目的,这是mystr在进入画布之前的样子:
REUTERS: Deadly twin suicide attack hits Damascus police station REUTERS: Police questioned suspect in Marseille knife killings prior to attack BLOOM: Oil Slides as Boost From Demand, Iraq Tension Seen as Temporary BLOOM: Pound May Have Hit Ceiling With Best Month Since 2015: Chart BLOOM: Libya Oil Output Is Said to Drop to Five-Month Low on Field Halt BLOOM: Qatar Fund Is Said to Explore Asset Sales as New Deals on Hold REUTERS: Fed's rate hikes causing low inflation, Kashkari says BLOOM: Playtika Acquires Israel's Jelly Button to Expand Game Offerings REUTERS: Editors Choice Pictures CB: Why the plebiscite was a disaster REUTERS: Wall Street indexes open at record highs REUTERS: U.S. construction spending rebounds after two straight monthly declines REUTERS: Fiat Chrysler will press on with Magneti Marelli separation next year: CEO CB: Melee in Catalonia as Spanish police violently attack voters CB: SBA opens business recovery center in hurricane-stricken Puerto Rico BLOOM: Prison Video Visits Are No Substitute for Face-to-Face, Especially at These Prices REUTERS: Uber's UK boss quits as firm battles to keep London license WSJ: The Link Between Economic Growth and Tax Cuts Is Tenuous REUTERS: Monarch's demise brings more headaches for holidaymakers WSJ: GOP Challenge With Tax Plan: How Far to Cut Rates for the Rich CB: Puerto Ricans denounce ‘second-class’ status as island struggles to recover REUTERS: U.S.-led coalition service member killed in Iraq: statement BLOOM: Trump Faces Leadership Test After Las Vegas Shooting BLOOM: Can the ‘Uber of Trash’ Clean Up Its Own Business? REUTERS: Calmer times may call for smaller, more extended ECB bond buys: Praet REUTERS: U.S. construction spending rebounds after two straight monthly declines REUTERS: Britain's Monarch Airlines goes bust, stranding thousands REUTERS: Kenyan police fire teargas at opposition protesters in capital REUTERS: Health and safety rules targeted to slash red tape REUTERS: U.S. Supreme Court rejects Samsung appeal in warranty dispute REUTERS: France's Macron backs Spain's constitutional unity in call to PM Rajoy CB: Melee in Catalonia as Spanish police violently attack voters REUTERS: Catalonia worries knock euro against stronger dollar REUTERS: Can't guarantee tax cut for entire middle class: Mnuchin BLOOM: Facebook's Season of Atonement Is Here REUTERS: Catalan leader calls for international mediation in Madrid stand-off BLOOM: Turkey Tourism Recovery No Lira Panacea as Europeans Stay Clear REUTERS: Dollar surges as Fed talk boosts Treasury yields REUTERS: U.S. Supreme Court rejects Samsung appeal in warranty dispute BLOOM: Banks’ Brexit Moving Costs Are Seen Topping $500 Million Each REUTERS: How we tick: U.S. 'body clock' scientists win Nobel medicine prize REUTERS: U.S. top court rejects New Zealand-based internet mogul's appeal CB: Government jobs sprouting as legal cannabis looms in California BLOOM: Automakers Plan Electric Car Blitz as Tesla Burns Billions REUTERS: EU urges Spain to talk to Catalans, condemns violence WSJ: GOP Tax Blueprint: Not Every Corporation Will Benefit REUTERS: Mozambique's President Nyusi will run for re-election in 2019 REUTERS: Bangladesh, Myanmar agree to draw up plan for refugee repatriation: minister REUTERS: Mnuchin says no regrets over government plane use BLOOM: This Cryptocurrency Gained 695% on a Deal With Visa That Didn’t Happen CB: At least 50 killed as gunman opens fire at Las Vegas concert BLOOM: Brexit Bulletin: Boris Watch CB: Trump signals critics of hurricane response will not cow him BLOOM: Manufacturing in U.S. Expands at Fastest Pace in 13 Years CB: EPA-assessed superfund sites unaffected by Hurricane María REUTERS: Uber’s path to win back London: data, fines and fees REUTERS: Google relaxes rules on free news stories, plans new tools REUTERS: Capitalism is the only way, UK finance minister says in challenge to Labour BLOOM: Europe on the Brink of Sugar Deluge as Decade-Long Curbs End BLOOM: Diamond Producers’ Shares Are Having a Rough 12 Months BLOOM: At Least 50 Killed as Gunman Opens Fire at Las Vegas Concert CB: [Annotation] The People Have Spoken BLOOM: Equifax Has Amassed Salary Details for People at 7,100 Companies REUTERS: Palestinian prime minister visits Gaza in reconciliation move with Hamas WSJ: China’s Central Bank Announces Targeted Easing to Boost Small-Business Loans CB: At least 50 killed as gunman opens fire at Las Vegas concert REUTERS: A cell signal, an open bar: tiny wins for Puerto Rico in ruins BLOOM: Euro Factories Add Jobs in Struggle to Keep Up With Orders CB: Trump signals critics of hurricane response will not cow him REUTERS: Disney, Altice shares gain after deal avoids blackout REUTERS: Facebook to give Russia-linked ads to U.S. Congress on Monday REUTERS: Monday Morning Briefing REUTERS: Interactive: Polling on the president CB: US school districts prepare for influx of Puerto Ricans CB: Catalonia calls for Spain mediation amid referendum dispute REUTERS: Britain will lobby U.S., Canada over Bombardier dispute: Hammond REUTERS: Bain says aims to buy Japan ad agency Asatsu-DK for $1.4 billion BLOOM: Warren Buffett Was Right About the Airlines WSJ: ECB’s Praet: Deflation Has Disappeared BLOOM: Uber's U.K. Head to Step Down Amid London Licensing Fight CB: Caribbean faces up to $30 billion in insured losses from María REUTERS: At least 50 dead in Las Vegas shooting REUTERS: Exclusive: Uber's UK boss quits as firm battles to keep London license - email REUTERS: Special Report: HP Enterprise let Russia scrutinize cyberdefense system used by Pentagon CB: San Juan mayor in hurricane spotlight after Trump tweets WSJ: Trump Met With Two Possible Candidates for Fed Chairman CB: Trump praises Puerto Rico aid, mayor says it’s ‘killing us’ REUTERS: Acute shortages plunge island into survival mode REUTERS: Wall Street indexes open at record highs BLOOM: Rising Borrowing Costs Weaken Canadian Consumer Confidence REUTERS: Trump to top U.S. diplomat: Don't bother talking to North Korea WSJ: Global Economy Week Ahead: Eurozone and U.S. Unemployment, India Rate Decision CB: García Padilla: Rubio Is No Friend of Puerto Rico REUTERS: Disney, Altice reach deal that avoids ESPN blackout REUTERS: Catalan leader calls for international mediation in Madrid stand-off BLOOM: Abe’s Support Falls in Two Polls Ahead of Snap Election REUTERS: Russian firm provides new internet connection to N.Korea REUTERS: Oil falls below $56 on signs of higher output CB: Trump signals critics of hurricane response will not cow him CB: Trump scoffs at ‘politically motivated ingrates’ after Maria REUTERS: Fed's rate hikes causing low inflation, Kashkari says BLOOM: Las Vegas Attack Is Deadliest Shooting in Modern U.S. History CB: Puerto Rico electric utility sets up generators to power island quickly REUTERS: Google relaxes rules on free news stories, plans subscription tools BLOOM: How to Turn $140,000 in Sales Into 4,000% in Stock Gains BLOOM: With His Stock Up 330%, a Serial Dealmaker Seeks Biggest Hit Yet BLOOM: Nordstrom Drops on Report Its Buyout Deal Is Losing Support REUTERS: Metro Inc to buy Jean Coutu Group in $3.60 billion deal CB: At least 50 killed as gunman opens fire at Las Vegas concert REUTERS: Islamic State hostages, strongholds stand between U.S.-backed forces and Raqqa's capture CB: María television reporting raises echoes of Katrina coverage REUTERS: U.S. top court rejects New Zealand-based internet mogul's appeal REUTERS: Merkel's Bavarian allies insist on conservative unity before coalition talks BLOOM: How Far Can the Catalan Rebellion Go? BLOOM: Hedge Funds Come Together to Share Cost of MiFID, Research CB: EPA-assessed superfund sites unaffected by Hurricane María WSJ: ISM Manufacturing Index Rises to 60.8 in September BLOOM: Metro to Sell Assets as Part of $3.6 Billion Jean Coutu Purchase REUTERS: Oil falls below $56 on signs of higher output REUTERS: For some elderly Americans, mortgage rules herald harder struggle BLOOM: Starbucks, Google Assailed by Investors Over Gender Policies
答案 0 :(得分:1)
画布对象的总宽度约为2 ^ 15(32768),在您的字体选择中约为4800个字符。要解决您的问题,您可以将文本限制为小于此值,或者在文本对象的边界框小于~30,000之后创建新对象。
移动文本对象的代码应该使用mainloop
而不是time.sleep
来实现。实现可能如下所示:
def move_text():
canvas.move(text, -1, 0)
root.after(10, move_text) # Time in milliseconds.
然后在move_text
之前致电mainloop
。
如果您希望拥有字符串的整个长度,那么您可以实现如下函数:
def check_text():
x = canvas.bbox(text)[0]
if x < -30000:
canvas.itemconfig(text, text=mystr[4808:])
canvas.move(text, 30000, 0)
请注意,在创建文本时,我在4808(系统上的限制)上拆分mystr
,因此我在画布上移动文本后将其修改为文本。
您还需要将check_text()
添加到move_text
。