2016-07-25 5 views
0

나는 Yahoo!를 읽는 Feedparser 모듈을 사용하는 뉴스 피드 프로그램을 만들고있다. RSS API를 사용하여 텍스트 파일에 키 데이터를 작성한 다음 Tkinter GUI로 구성된 데이터를 표시하십시오.Tkinter 메시지 위젯에 하이퍼 링크를 표시 할 수 있습니까?

텍스트 파일/Tkinter 메시지 위젯에서 클릭 가능한 하이퍼 링크를 가질 수 있는지 묻는 중입니다.

텍스트 파일의 항목이 포함되어있는 경우
  • 는 'HTTP'이 하이퍼 링크합니다

    나의 현재의 생각은 다음과 같은 방식으로 실행되는 코드를 작성할 수 있다는 것입니다.

누군가 달성 할 수있는 Pythonic 방식을 알고 있거나 실제로 가능하지 않다는 것을 알고 있다면 기여하십시오. 내가 본 콜백을 트리거하기 위해 웹 브라우저 사용하고 Tkinter의 객체에 이벤트를 부착 참여 가지고 Tkinter의 응용 프로그램에서 하이퍼 링크의

def news_feed(event): 
    ''' This function creates a new window within the main window, passes an event(left mouse click), and creates a text heading''' 

    root = Toplevel(window) 

    # Create a text heading and define its placement within the grid 
    menu_heading = Label(root, text = 'News feed', font = 'bold') 
    menu_heading.grid(row = 0, column = 0, columnspan = 3, pady = 4) 

    # Create a variable of the selected radio button 
    button_choice = IntVar() 

    def selection(): 
     ''' This function gets the activated radio button and calls its corresponding function.''' 

     # Get the value of the activated radio button, and call its corresponding function 
     news_choice = button_choice.get() 

     # If the user's choice is industry news, ask them which feed they would like (E.g. Stock market), 
     if news_choice == 0: 
      # grab the corresponding url segment to the user's feed choice from the dictionary, 
      news_choice_url = news_areas[news_feed] 
      # set the url variable using by inserting this segment into the API url, 
      rss_url = feedparser.parse('https://au.finance.yahoo.com/news/' + news_choice_url + '/?format=rss') 
      # and call the feed parsing function. 
      parse_feed() 
     # If the user's choice is the second button, call the company news function 
     elif news_choice == 1: 
      company_news() 

    def read_news_file(news_feed_message): 
     '''This function opens the companyNews text file and reads its contents, line by line''' 
     with open('C:\\Users\\nicks_000\\PycharmProjects\\untitled\\SAT\\GUI\\Text Files\\companyNews.txt', mode='r') as inFile: 
      news_data_read = inFile.read() 
      print('\n') 
     news_feed_message.configure(text = news_data_read) 

    def parse_feed(news_feed_message, rss_url): 
     ''' This function parses the Yahoo! RSS API for data of the latest five articles, and writes it to the company news text file''' 

     # Define the RSS feed to parse from, as the url passed in of the company the user chose 
     feed = feedparser.parse(rss_url) 

     try: 
      # Define the file to write the news data to the company news text file 
      with open('C:\\Users\\nicks_000\\PycharmProjects\\untitled\\SAT\\GUI\\Text Files\\companyNews.txt', mode='w') as outFile: 

       # Create a list to store the news data parsed from the Yahoo! RSS 
       news_data_write = [] 
       # Initialise a count 
       count = 0 
       # For the number of articles to append to the file, append the article's title, link, and published date to the news_elements list 
       for count in range(10): 
        news_data_write.append(feed['entries'][count].title) 
        news_data_write.append(feed['entries'][count].published) 
        article_link = (feed['entries'][count].link) 
        article_link = article_link.split('*')[1] 
        news_data_write.append(article_link) 
        # Add one to the count, so that the next article is parsed 
        count+=1 
        # For each item in the news_elements list, convert it to a string and write it to the company news text file 
        for item in news_data_write: 
         item = str(item) 
         outFile.write(item+'\n') 
        # For each article, write a new line to the company news text file, so that each article's data is on its own line 
        outFile.write('\n') 
        # Clear the news_elements list so that data is not written to the file more than once 
        del(news_data_write[:]) 
     finally: 
      outFile.close() 

     read_news_file(news_feed_message) 

    def industry_news(): 
     ''' This function creates a new window within the main window, and displays industry news''' 

     industry_window = Toplevel(root) 
     Label(industry_window, text = 'Industry news').grid() 

    def company_news(): 
     ''' This function creates a new window within the main window, and displays company news''' 

     company_window = Toplevel(root) 
     company_label = Label(company_window, text = 'Company news') 
     company_label.grid(row = 0, column = 0, columnspan = 6) 

     def company_news_handling(company_ticker): 
      ''' This function gets the input from the entry widget (stock ticker) to be graphed.''' 

      # set the url variable by inserting the stock ticker into the API url, 
      rss_url = ('http://finance.yahoo.com/rss/headline?s={0}'.format(company_ticker)) 
      # and call the feed parsing function. 
      parse_feed(news_feed_message, rss_url) 

     # Create the entry widget where the user enters a stock ticker, and define its location within the grid 
     company_ticker_entry = Entry(company_window) 
     company_ticker_entry.grid(row = 1, column = 0, columnspan = 6, padx = 10) 

     def entry_handling(): 
      '''This function validates the input of the entry box, and if there is nothing entered, an error is outputted until a value is''' 

      # Create a variable that equals the input from the entry widget 
      company_ticker = company_ticker_entry.get() 

      # Convert the input into a string 
      company_ticker = str(company_ticker) 

      if company_ticker == '': 
       news_feed_message.configure(text = 'Please input a stock ticker in the entry box.') 
      else: 
       company_news_handling(company_ticker) 

     # Create the button that the user presses when they wish to graph the data of the stock ticker they inputted in the entry widget 
     graph_button = Button(company_window, text = 'SHOW', command = entry_handling, width = 10).grid(row = 2, column = 0, columnspan = 6) 

     news_feed_message = Message(company_window, text='', width=500, borderwidth=5, justify=LEFT, relief=RAISED) 
     news_feed_message.grid(row=3, column=0, columnspan=6) 

답변

1

대부분 사용하지만이 :

이 당신의 시간을 주셔서 감사합니다, 여기에 내 코드입니다 간단한 방법으로 만 할 수있다을 heres 내가 무엇을 의미하는지 :이 source

당신이 말한대로이 할 수있는

다시에서

from tkinter import * 
import webbrowser 

def callback(event): 
    webbrowser.open_new(r"http://www.google.com") 

root = Tk() 
link = Label(root, text="Google Hyperlink", fg="blue", cursor="hand2") 
link.pack() 
link.bind("<Button-1>", callback) 
root.mainloop() 

광고를 텍스트 파일에서 가져오고, 줄에 "http"가 포함되어 있으면 파일에서 하이퍼 링크를 이벤트에 첨부하여 새 레이블 및 이벤트를 만듭니다.

import re 

with open(fname) as f: 
    content = f.readlines() 
    urls = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[[email protected]&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', content) 

액세스 URL의이 후 및 생성은 라벨의 또는 어떤 위젯은이 URL을 너무 첨부 당신은 클릭 할 때 그들 모두가 웹 페이지를 열 수 있습니다. 이 어떤 식 으로든 도움이

희망, 당신은 내가 그것을 다음 링크를 따라 수정하는 쉬운을 사용하여 Tkinter의에서 하이퍼 링크를 쉽게 만들 생각 도움 :

0

The output

필요하면 알려주세요

Updated Hyperlink in tkinter

희망 귀하의 요구 사항이 당신을 위해 작동합니다.

안부 Midhun

+0

"하이퍼 링크 in tkinter"는 tkinter의 하이퍼 링크와 관련이없는 페이지로 연결됩니다. –

+0

링크 체크 아웃을 업데이트했습니다. –