Python using(parsing) a textbox value as string into a function - python

url=StringVar()
txt1=Entry(root,textvariable=url)
txt1.pack()
button1 = Button(root, text="Download" ,command=downloadFile)
button1.pack()
root.mainloop()
ok this is my basic GUI... I have a textbox txt1 which i want to use in the function below
def downloadFile():
#print "url is:",url
file_name = url.split('/')[-1]
My aim is to feed in the URL in the textbox and then split the URL in my function downloadfile(), but my url variable becomes PY_VAR0 instead of "www.example.com/file.exe"
and the error message I get is "StringVar instance has no attribute split"
I am doing something very wrong but i don't know where.
Can anyone help please?

StringVar is just a "Value holder for strings variables". To get its content (the string) use:
StringVar.get() # Return value of variable as string.
printing the StringVar directly ("print url") invokes:
StringVar.__str__() # Return the name of the variable in Tcl.
which will return the internal variable name, not its value. in your code use:
file_name = url.get().split('/')[-1]

Related

Python ttk combobox value update?

I use a GUI for some web automation with selenium.
I have several comboboxes (will do one example here)
This is my example code:
app = Tk()
def callback(*args): # should get the updated values in Combobox ?
global v_sv_league
v_sv_league = str(sv_league.get())
#List to be filled by scraper
li_leagues = []
#StringVar
sv_league = StringVar()
sv_league.trace("w", callback)
#Label
l_d_league = tk.Label(app,text='League:',bg='#1d1b29', fg='#f8f09d',font='Tahoma 10')
#Combobox
d_league = ttk.Combobox(app,textvariable=sv_league,values=li_leagues)
#Scrape
def scrape():
btn_tflist = wait.until(EC.element_to_be_clickable((By.XPATH,('/html/body/main/section/nav/button[3]'))))
btn_tflist.click()
btn_tf_filters = wait.until(EC.element_to_be_clickable((By.XPATH,'/html/body/main/section/section/div[2]/div/div/div[2]/div[2]')))
btn_tf_filters.click()
bol_scrape = True
if bol_scrape is True:
print('\n Start scraping... this might take a few minutes. Please wait and dont press anything until trade_buddy is done!\n')
li_leagues = []
print('Getting leagues...\n')
league_dropdown_menu = wait.until(EC.element_to_be_clickable((By.XPATH,('/html/body/main/section/section/div[2]/div/div[2]/div/div[1]/div[1]/div[7]/div'))))
league_dropdown_menu.click()
time.sleep(1)
# scrape all text
scrape_leagues = driver.find_elements_by_xpath("//li[#class='with-icon' and contains(text(), '')]")
for league in scrape_leagues:
export_league = league.text
export_league = str(export_league)
export_league = export_league.replace(',', '')
li_leagues.append(export_league)
app.mainloop()
So basically this is just a small part of my code but this is what I got for one of my combobox's.
You can see that I will call for def scrape at some point in my code to scrape data and to fill my list li_leagues.
However, my combobox is not refreshing the content and stays empty.
For OptionMenu I got it set up (with a it other code) but I cant get it working with combobox.
Any advice what I am missing here?
Thanks a slot!
Try using this line of code, after appending the list with values.
.....
export_league = export_league.replace(',', '')
li_leagues.append(export_league)
c_league.config(values=li_leagues)
config() method acts as a updater that just updates your widget, when called.
Hope it was of some help.
Cheers

How would you use tkinter to create a basic translator?

I have made the "GUI". I had a drop-down menu but can't figure out how to make that work. I tried using switch cases i.e.:
def language(i):
switcher = {
0 : 'german'
1 : 'russian'
}
return switcher.get(i, "Invalid language")
In my other post I've mentioned how I tried to make it:
def rustrans():
word = entry.get()
translator = Translator(service_urls=["translate.google.com"])
translation = translator.translate(word, dest = "ru")
label = tk.Label(root, text = f"Russian text : {translation.text}", bg="yellow")
label.grid(row=2,column=0)
I tried using if-statements like:
if language(1):
btn = tk.Button(root, text="Translate", command=rustrans)
btn.grid(row=1,column=2)
elif language(0):
...
I do have my labels, entry etc but when I try to switch the language (I had a drop-down but that didn't work, when I would change the language in there and pressed the translate button it would still prefer translating Russian instead of German i.e.
How am I supposed to make it so when I change the language from the drop-down (I can bring it back, although I've removed it) and press translate, it translates the right language?
It's not clear what the problem is. You just need to associate a variable with the dropdown, and then get the value when you do the translation.
For example, let's assume the languages are defined in a global named LANGUAGES. The keys of the dictionary will be used in the UI, and the values are what is passed to the translator.
LANGUAGES={
'German': 'de',
'Russian': 'ru',
}
We can use the keys to populate a combobox, and then use the combobox value to get value to pass to the translator.
class TranslatorUI:
def __init__(self):
...
self.translator = Translator(service_urls=["translate.google.com"])
self.dest_var = tk.StringVar(value="German")
self.dropdown = ttk.Combobox(
self.root, textvariable=self.dest_var,
values=[str(x) for x in LANGUAGES.keys()]
)
self.word_entry = ttk.Entry(self.root)
self.button = ttk.Button(self.root, text="Translate", command=self.translate)
...
def translate(self):
word = self.word_entry.get()
language_name = self.dest_var.get()
lang = LANGUAGES[language_name]
self.translator.translate(word, lang)

Can't understand why function doesn't work

I'm new to Python3 and coding. I'am get stuck with a simple function.
import datetime
date = str(datetime.date.today())
mail = ""
text = (f"""
some text {mail}
some text {date}
some text
""")
print(text)
def get_deadline_date():
mail = "a#a.com"
print(text)
And I have
some text
some text 2019-03-21
some text
some text
some text 2019-03-21
some text
I can't change the text variable.
It should print:
some text a#a.com
some text 2019-03-21
some text
As I understand, I made a simple mistake, but I can't figure it out.
I tried,
import datetime
date = str(datetime.date.today())
mail = ""
text = (f"""
some text {mail}
some text {date}
some text
""")
print(text)
def get_deadline_date():
global mail
mail = "a#a.com"
get_deadlin
It gave the same output.
Your function is defined but not executed. And, if it was executed, it would not change the value of mail because it has it's own namespace of variables, so it could access mail but not set it. What you are doing there is declaring a new variable, also called mail in that function. On top of that, your text is already set and will not update when you chnge the value of mail. I suggest this solution:
text = "some text {mail}\n" \
"some text {date}\n" \
"some text"
def make_text(text, date):
mail = "a#a.com"
return text.format(mail=mail, date=date)
text = make_text(text=text, date=date.today())
You may also want to make separate functions for setting mail and making the text, but remember to return the new mail you make to the outer scope.
Mistake 1: You are not calling the function
Mistake 2: mail is local variable (to function)
Mistake 3: String is already evaluated/initialised
Bad, but your solution should be
import datetime
date = str(datetime.date.today())
mail = ""
text = """
some text {0}
some text {1}
some text
""".format
print(text(mail, date))
def get_deadline_date():
global mail
mail = "a#a.com"
get_deadline_date()
print(text(mail, date))
Avoid global variable
Dedesign your code to avoid global variable, use function parameters and return values instead.

Python Entry Button Submit issues

Currently with the below code I seem to be getting a weird issue as well cant seem to get the value of refreshtoken when I click the submit button. I do get the print for word but for refreshtoken I receive .!entry in the Console.
def getCommand(r):
print('word')
print(r)
tokenWindowFrame = Tk()
tokenWindowFrame.title("Add Character")
refreshLabel = ttk.Label(tokenWindowFrame, text="Refresh Token : ")
refreshLabel.grid(row=1,column=1)
refreshToken = ttk.Entry(tokenWindowFrame, width = 50)
refreshToken.grid(row=1,column=2)
button = ttk.Button(tokenWindowFrame, text = "Submit", command=lambda
r=refreshToken: getCommand(r))
button.grid(row=3,column=2)
tokenWindowFrame.mainloop()
You can't print an entry object, you need to print the text in the entry object. Use:
refreshToken.get()
I ended up having to change this line
button = ttk.Button(tokenWindowFrame, text = "Submit", command=lambda r=refreshToken: getCommand(r))
To :
button = ttk.Button(tokenWindowFrame, text = "Submit", command=lambda r=refreshToken: getCommand(r.get()))
The r.get() is what I was missing. As both print(r.get()) would not work in the Function.
To get the text in an entry box you need:
<entry_box>.get()
If you are trying to print it then you could just do:
print(<entry_box>.get())
Or in your case:
print(r.get())
Hope this works for you!

Python Tkinter - How to place the input from an entry using entry.get()

I have an entry named "Username".
username = Entry()
username.place(x = 10, y = 50)
and a submit button
submit = Button(text="Submit", command=getInfo)
submit.place(x = 150, y = 48)
It calls a getInfo function
def getInfo():
user = username.get()
I'd like to place user as a label. I can print it just fine, the text shows up in the console. When I try to place, I get an error.
File "tk.py", line 8, in getInfo
user.place(x = 150, y = 90)
AttributeError: 'str' object has no attribute 'place'
As the error message says: user is a string. You know it's a string, because you got it from an Entry widget using get(), which returns a string. You need to make a new widget to hold this string, and place that.
Like the error message says, user is a string and not a widget. Hence it doesn't have a place method like username and submit. You want to stick it into a label and then place the label.

Categories