Python Entry Button Submit issues - python

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!

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 to not display duplicates in a list using tkinter

How do I get this program to not display the same selection again to the user when its already been selected ?
I know behind the scenes I can create a set of my entries for the code to continue using, but I cant seem to stop the display showing duplicate items if the user selects the same thing again. I thought the 'not in' statement might have worked. Any help please ?
from tkinter import *
from tkinter import ttk
root = Tk()
# set in pixels
root.geometry("1000x750+100+100")
my_list = set()
def combo_click(event):
my_label = Label(root, text=myCombo.get()).pack()
if myCombo.get() not in my_list:
my_list.add(myCombo.get())
# print('List without duplicate items (Set) ' + '\n')
OptionList = [
"Aries",
"Taurus",
"Gemini",
"Cancer"
]
clicked = StringVar()
clicked.set(OptionList[0])
# *Options - https://docs.python.org/3/tutorial/controlflow.html#unpacking-argument-lists
#drop = OptionMenu(root, clicked, *OptionList, command=selected)
#drop.pack(pady=100)
myCombo = ttk.Combobox(root, value=OptionList)
myCombo.current(0)
myCombo.bind("<<ComboboxSelected>>", combo_click)
myCombo.pack()
root.mainloop()
A method you could use to filter out duplicates in a list is the following code. I am assuming you are adding each bit of text to the Tkinter list through variables.
In my code the variable: a is the item we wish to add to the list.
Code to filter through entries to a Tkinter list:
While True: #replace the bit inbetween w and t with your how long you want to do it
#add everything you add to a list before you add to Tkinter Listbox as shown below.
for x in tlist:
if tlist contains a:
print("Duplicate! This will not be added.")
else:
[whatever_you_called_your_listbox].insert(END,a)
print(a,"Was added.")
Hope this helps!

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)

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.

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

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]

Categories