I have an array of values . I have to show this list in a TwoLineIconListItem in kivy along with an image icon and with other information in a list view. When the user clicks on any of the list item, a popup should come (preferably a dialog) and I have to show the item text selected...Pls do help !!
I could write everything but it seems like I am unable to pass the value to the dialog from my TwoLineIconListItem...the code snippet is here where I need some help to achieve this please...
while counter < len(list_of_names):
self.party_name = list_of_names[counter]
self.party_pic = IconLeftWidget(icon=image_source + "\\" + list_of_names[counter].lower() + ".png")
counter += 1
items = TwoLineIconListItem(text=str(counter) + " : " + self.party_name,
secondary_text=self.party_name_details,
on_release=self.select_item)
items.add_widget(self.party_pic)
list_view.add_widget(items)
screen.add_widget(scroll)
return screen
def select_item(self, obj):
print(obj)
# It's should print the item text selected
close_btn = MDFlatButton(text="Close", on_release=self.close_dialog)
confirm_btn = MDFlatButton(text="I Confirm !", on_release=self.confirm_choice)
self.dialog = MDDialog(title="Please confirm your choice!",
text=self.party_name,
size_hint=(0.7, 1),
buttons=[close_btn, confirm_btn]
)
self.dialog.open()
Related
Essentially, I am trying to have a scoreboard, which upon completion of a task, opens the scoreboard and displays what your score is. However, whenever I run the actual task, it displays the initial value instead of the new variable value. How could I update this value within the window panel?
Sample Pseudocode:
from ursina import *
score=0
def challenge():
score += 2
wp.enabled=True
app = Ursina()
wp = WindowPanel(content=(Text('text' + str(score))) popup=True, enabled=False)
start = Button(parent=scene, text='start', on_click=challenge)
app.run()
Assign the text entity to a variable first:
text_entity = Text('text' + str(score))
wp = WindowPanel(content=(text_entity,) popup=True, enabled=False)
# to update the text
text_entity.text = 'new text'
What is happening is that your not assigning a variable to the Text which is bad. See:
wp = WindowPanel(content=(Text('text' + str(score))) popup=True, enabled=False)
When You assign it, you can change the information and content.
text = Text('text' + str(score))
wp = WindowPanel(content=(text) popup=True, enabled=False)
If you want to do something like if a key is pressed, then see this code:
text = Text('text' + str(score))
wp = WindowPanel(content=(text) popup=True, enabled=False)
def update():
I am using vuetify to catch an input of a user as follows:
%pip install ipyvuetify
%pip install ipywidgets
import random
import ipywidgets as widget
from ipywidgets import VBox
import ipyvuetify as v
v_nr = v.TextField(label='Enter a number here:', placeholder='Enter here data', value = '2342354')
v_nr.value='The value was changed sucssefully'
v_btn_load = v.Btn(class_='mx-2 light-red darken-1', children=['the data'])
w_Output = widget.Output()
infostring = ' this is the infostring there'
other_info = v.Html(tag='p', children=[infostring])
Output = VBox([w_Output])
total_widgets = v.Col(children = [v_nr,v_btn_load,w_Output,other_info])
def on_click_v_btn_load(widget, event, data):
with w_Output:
w_Output.clear_output()
n = random.random()
display(str(n) + ' :' + v_nr.value)
other_info.children.append(' APPEND ')
v_btn_load.on_event('click', on_click_v_btn_load)
container = v.Container(children=[total_widgets])
display(container)
What I would like to solve:
The visualization is ok but when changing the value in the input it is not catched by the v_application.value within the event handler of the button. Nevertheless in the second line: v_nr.value='The value was changed successfully' the value was changed programatically. How do you have to code in order the input changes the value of the input text when the user changes it?
other_info.children.append(' APPEND ') does not seem to work but does not report neither error. What is expecting is that the word GORILA is appended every time the button is clicked, and that is not the case.
Any ideas?
Thx.
NOTE: included %pips for convinience.
the property of v_nr to access the content is 'v_model', not 'value'.
by simply changing this it works:
import random
import ipywidgets as widget
from ipywidgets import VBox
import ipyvuetify as v
v_nr = v.TextField(label='Enter a number here:', placeholder='Enter here data', v_model = '2342354')
v_nr.v_model='The value was changed sucssefully'
v_btn_load = v.Btn(class_='mx-2 light-red darken-1', children=['the data'])
w_Output = widget.Output()
infostring = ' this is the infostring there'
other_info = v.Html(tag='p', children=[infostring])
Output = VBox([w_Output])
total_widgets = v.Col(children = [v_nr,v_btn_load,w_Output,other_info])
def on_click_v_btn_load(widget, event, data):
with w_Output:
w_Output.clear_output()
n = random.random()
display(str(n) + ' :' + v_nr.v_model)
other_info.children.append(' APPEND ')
v_btn_load.on_event('click', on_click_v_btn_load)
container = v.Container(children=[total_widgets])
display(container)
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I am creating a GUI that is meant to emulate an online shop of some sort.
One part of the task is to have a button that will generate a HTML document with images of the user's chosen product category.
Below I have provided my four radio buttons along with their IntVar and commands.
Each of the RadioButton commands do the same thing but extract information from different websites, so for brevity I have only provided the command for the slipper category.
home_hobbies = Tk()
status = IntVar()
def show_slippers():
#open downloaded file to extract info
slipperfile = open('slippers.html','r',encoding = 'utf-8').read()
prices = findall("<span.*value'>(.*)</span>", slipperfile) #regex prices
titles = findall('<h3.*body ">\n\s*(.*)', slipperfile) #regex titles
select_categ.config(state=NORMAL) #make the text box edit-able
select_categ.delete(1.0, END) #delete any text already in the text box
#for loop to find first five items and print them
for i in range(5):
title = titles[i]
price = prices[i]
result = str(i+1) + ". " + title + ' - $' + price + "\n"
select_categ.insert(END, result) #write list of products
select_categ.config(state=DISABLED) #make sure the user can't edit the text box
slippers = Radiobutton(home_hobbies, command = show_slippers, indicator = 'off', variable = status, value = 1, text = 'Winter Slippers')
diy = Radiobutton(home_hobbies, command = show_diy, indicator = 'off', variable = status, value = 2, text = "DIY Supplies")
#newstock radiobuttons
sports = Radiobutton(home_hobbies, command = show_sports, indicator = 'off', variable = status, value = 3, text = "Pool Toys")
novelties = Radiobutton(home_hobbies, command = show_novelties, indicator = 'off', variable = status, value = 4, text = "Novelty Items")
select_categ = Text(home_hobbies, wrap = WORD, font = content_font, bg = widgetbg, fg = fontcolour, width = 40)
Above, I also provided the line of code that generates the Text widget as it may help in answering my question (I don't have a very deep understanding of this widget despite reading the effbot page about 20 times over).
I now have a different button whose task is to generate a HTML doc with it's own command, "show_img":
htmlshow = Button(home_hobbies, text = "View Product Images", command = show_img)
I am trying to make the show_img() command work such that I have a preamble of HTML coding, and then, depending on which radibutton has been chosen, the function will replace sections of the code with the corresponding information:
def show_img():
#in this section I write my HTML code which includes replaceable sections such as "image1" and source_url
if slipper_trig:
table = table.replace("source_url", ' Etsy - Shop Unique Gifts for Everyone')
imgfile = open('slippers.html', 'r', encoding = 'utf-8').read()
images = findall('<img\n*.*image\n*\s*src="(.*)"', imgfile)
for i in range(5):
image = images[i]
table = table.replace("image"+str(i+1), image)
I tried to add BooleanVar into the commands for my Radio Buttons like this:
slipper_trig = False
diy_trig = False
pool_trig = False
novelty_trig = False
#Function for the product category buttons
#
def show_slippers():
#make selected category true and change all others to false
slipper_trig = True
diy_trig = False
pool_trig = False
novelty_trig = False
As a way to distinguish between the categories but the GUI clearly doesn't remember the value of "slipper_trig" after its been defined as true in the "show_slippers" function.
Maybe I need to try and integrate the "show_img" command into my original functions that define the RadioButtons? Maybe I should be figuring out how to determine the category chosen by what's shown in the text box?
Any advice would be appreciated.
Thanks!
You didn't show minimal working code with your problem so I can only show some minimal example with Button and RadioButton to show how to use these widgets.
I don't know if you used command=function_name in Button.
BTW: it has to be function's name without ()
I don't know if you used .get() to get value from StringVar/Intvar/BooleanVar assigned to RadioButtons.
EDIT I added Checkbutton because probably you may need it instead of Radiobutton
import tkinter as tk
# --- functions ---
def on_click():
selected = result_var.get()
print('selected:', selected)
if selected == 'hello':
print("add HELLO to html")
elif selected == 'bye':
print("add BYE to html")
else:
print("???")
print('option1:', option1_var.get()) # 1 or 0 if you use IntVar
print('option2:', option2_var.get()) # 1 or 0 if you use IntVar
if option1_var.get() == 1:
print("add OPTION 1 to html")
if option2_var.get() == 1:
print("add OPTION 2 to html")
# --- main ---
root = tk.Tk()
result_var = tk.StringVar(root, value='hello')
rb1 = tk.Radiobutton(root, text="Hello World", variable=result_var, value='hello')
rb1.pack()
rb2 = tk.Radiobutton(root, text="Good Bye", variable=result_var, value='bye')
rb2.pack()
option1_var = tk.IntVar(root, value=0)
opt1 = tk.Checkbutton(root, text='Option 1', variable=option1_var)
opt1.pack()
option2_var = tk.IntVar(root, value=0)
opt2 = tk.Checkbutton(root, text='Option 2', variable=option2_var)
opt2.pack()
button = tk.Button(root, text='OK', command=on_click)
button.pack()
root.mainloop()
Doc on effbot.org: Button, Radiobutton, Checkbutton
I created a table widget and added a contextmenu to it. When I right click the cell,I want to get a file directory and put it into the cell. I've got the directory and pass it to a variable, but i failed to display it in the cell,because I can't get the index of the cell.How to get index of a cell in QTableWidget? Is there any orther method to figure out this qusstion? I'm using Python and PyQt5.
enter image description here
#pyqtSlot()
def on_actionAddFolder_triggered(self):
# TODO: Open filedialog and get directory
filedir = str(QFileDialog.getExistingDirectory(self, "Select Directory"))
return filedir
#pyqtSlot(QPoint)
def on_tableWidget_customContextMenuRequested(self, pos):
# TODO: get directory and display it in the cell
x = self.tableWidget.currentRow
y = self.tableWidget.currentColumn
RightClickMenu = QMenu()
AddFolder = RightClickMenu.addAction('Add Folder')
FolderAction = RightClickMenu.exec_(self.tableWidget.mapToGlobal(pos))
if FolderAction == AddFolder:
NewItem = QTableWidgetItem(self.on_actionAddFolder_triggered())
self.tableWidget.setItem(x,y, NewItem)
hahaha, I find the mistake!
x = self.tableWidget.currentRow
y = self.tableWidget.currentColumn
replace these two lines
x = self.tableWidget.currentRow()
y = self.tableWidget.currentColumn()
then it works.
I am creating a news feed program that uses the Feedparser module to read the Yahoo! RSS API, write key data to a text file, and then display the data organised in a Tkinter GUI.
I was enquiring if it is possible to have clickable hyperlinks in a text file/Tkinter message widget.
My current thinking is that you could write code that runs in the following fashion:
If item in the text file includes 'http', make it a hyperlink.
If anyone knows of a Pythonic way to achieve this, or knows if it is not in fact possible, please contribute.
Thank you for your time, here is my code:
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)
Most uses of hyperlinks in a tkinter application i have seen involved using the webbrowser and attaching events to your tkinter object to trigger callbacks, but there may be simpler ways, but heres what i mean :
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()
From this source
You could do as you said and read from a text file, and if the line contains "http" create a new label, and event, attaching the hyper link from the file to the event.
import re
with open(fname) as f:
content = f.readlines()
urls = re.findall('http[s]?://(?:[a-zA-Z]|[0-9]|[$-_#.&+]|[!*\(\),]|(?:%[0-9a-fA-F][0-9a-fA-F]))+', content)
Access the url's after this and generate your label's or whatever widget you attach the url's too and you can then have all of them open the web page when clicked.
Hope this helps in some way, let me know if you need more help :)
I think it is easy to create hyperlink in tkinter using following link and its easy for modifying as per your requirement
Updated Hyperlink in tkinter
hope this works for you.
regards Midhun
(Answer taken from effbot)
Support module for Text hyperlinks (File: tkHyperlinkManager.py)
from Tkinter import *
class HyperlinkManager:
def __init__(self, text):
self.text = text
self.text.tag_config("hyper", foreground="blue", underline=1)
self.text.tag_bind("hyper", "<Enter>", self._enter)
self.text.tag_bind("hyper", "<Leave>", self._leave)
self.text.tag_bind("hyper", "<Button-1>", self._click)
self.reset()
def reset(self):
self.links = {}
def add(self, action):
# add an action to the manager. returns tags to use in
# associated text widget
tag = "hyper-%d" % len(self.links)
self.links[tag] = action
return "hyper", tag
def _enter(self, event):
self.text.config(cursor="hand2")
def _leave(self, event):
self.text.config(cursor="")
def _click(self, event):
for tag in self.text.tag_names(CURRENT):
if tag[:6] == "hyper-":
self.links[tag]()
return
And here’s an example:
# File: hyperlink-1.py
import tkHyperlinkManager
from Tkinter import *
root = Tk()
root.title("hyperlink-1")
text = Text(root)
text.pack()
hyperlink = tkHyperlinkManager.HyperlinkManager(text)
def click1():
print "click 1"
text.insert(INSERT, "this is a ")
text.insert(INSERT, "link", hyperlink.add(click1))
text.insert(INSERT, "\n\n")
def click2():
print "click 2"
text.insert(INSERT, "this is another ")
text.insert(INSERT, "link", hyperlink.add(click2))
text.insert(INSERT, "\n\n")
mainloop()