Hiram Ruiz Hiram Ruiz - 1 year ago 122
Python Question

Canvas.move() Halting Unexpectedly

So i'm making a ticker that will display scraped news headlines at the top of my screen. After scraping, I turned all the headlines into a single line string (about 8000 characters) in order to continuously scroll it trough the ticker (tkinter canvas with text+move).

However, halfway into the text it simply stops moving. There is text after that still undisplayed. After checking the txt. file the string comes from, there is nothing special about the place where it halts. No line breaks, tabs or special characters. Thats what makes me think it has to do with the single line of text being simply too long for it to display... I also increased the canvas height to see if it was doing any type of wrapping that left text in the line beneath, but that was not the case. Hopefully someone here will know what's up. Thanks.

Code:

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()


For testing purposes, this is what mystr looks like before going into the canvas:

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

Answer Source

The total width of canvas objects is about 2^15 (32768), which in your font choice is about 4800 characters. To fix your issue you can either limit the text to less than this, or create a new object after the bounding box of your text object is less than ~30,000.

Your code to move the text object should be implemented with the mainloop as opposed to with time.sleep. An implementation could look like this:

def move_text():
    canvas.move(text, -1, 0)
    root.after(10, move_text)  # Time in milliseconds.

And then call move_text just before the mainloop.

If you wish to have the entire length of the string, then you could implement a function such as this:

def check_text():
    x = canvas.bbox(text)[0]
    if x < -30000:
        canvas.itemconfig(text, text=mystr[4808:])
        canvas.move(text, 30000, 0)

Note that I have split mystr at 4808 (The limit on my system) when creating the text, so I modify it to the text thereafter when moving it on the canvas. You will also need to add check_text() to move_text.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download