Tkinter entry for variable - python

i've red a lot of post here and i couldn't find a clue on my problem even if it was repeated a lot, it doesn't really apply to my case.
My code is simple. I have a string, i want to create the wordcloud of this string, but i also created a function that gets in entry an integer, and returns the wordcloud with the number of words in the variable. My code works well alone, my function is called "test_wordcloud". If i enter "test_wordcloud(4)" for example, it will return the wordcloud with the 4 most present words in the string.
def test_wordcloud(n):
if type(n) == "int":
wordcloud = WordCloud(width=900, height=400, background_color="white", max_font_size=125,
min_font_size=20, max_words=n).generate(string)
fig = plt.figure(figsize = (10, 10))
plt.axis("off")
plt.imshow(wordcloud)
fig.savefig("Test Tkinter.jpg", bbox_inches='tight', dpi=150)
source_path = "C:\\Users\\f002722\\Stage NLP\\Test Tkinter.jpg"
destination_path = "C:\\Users\\f002722\\Desktop\\NLP4DTV 2.0\\results\\data\\Test Tkinter.jpg"
shutil.move(source_path, destination_path)
return "DONE"
Now i want to make a Tkinter interface where the user enter the number of words he wants, then the wordcloud in format jpg is created in the folder up there and he can see it. But it doesn't work. So far i've done like this.
import tkinter as tk
from tkinter import ttk
from tkinter.messagebox import showinfo
root = tk.Tk()
root.title("WordCloud configuration")
title = root.title()
window_width = 300
window_height = 300
# Center the window
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
center_x = int(screen_width/2 - window_width / 2)
center_y = int(screen_height/2 - window_height / 2)
root.geometry(f'{window_width}x{window_height}+{center_x}+{center_y}')
wordnumber = tk.StringVar()
wordnumberlabel = ttk.Label(root, text = "Number of words").pack()
entry = ttk.Entry(root, textvariable = wordnumber)
entry.pack()
ttk.Button(root, text = "Ok", command = test_wordcloud(entry.get())).pack()
root.mainloop()
I really don't see where i'm wrong, my command on the button is "test_wordcloud(entry.get())" which should guarantee my code to run this function with the entry, but when i do so, nothing happens. The window opens with the button and the place where to right the variable but when i press "ok" nothing happens.
I woudl really appreciate help her because i keep looking for answer on google but i feel stuck, thx in advance

Related

after clicking my window goes not responding can any one hlep?

when I click the button it call's cpuTemp function and it has a after loop init which causes my not responding window and it is show values of cpu percent in my python console so the question is why it is not working
'''
from tkinter import *
import psutil
import statistics
window = Tk()
# window size
screen_width = window.winfo_screenwidth()
screen_height = window.winfo_screenheight()
# window
window.attributes('-transparentcolor', 'blue')
window.resizable(True, True)
window.attributes('-alpha', 0.96)
window.config(cursor='crosshair')
window.attributes('-topmost', 0)
window.geometry(f"{screen_width}x{screen_height}+20+20")
window.state('zoomed')
window.title('Hello Python')
# windTemp
def cpuTemp(event):
#gettin temps
cpuTemps = [psutil.cpu_percent(0.5), psutil.cpu_percent(0.5), psutil.cpu_percent(0.5),
psutil.cpu_percent(0.5), psutil.cpu_percent(0.5)]
meanVal = statistics.mean(cpuTemps)
print(meanVal)
lbl.configure(text=f'{meanVal}%')
window.after(1000 , cpuTemp(event))
#button
btn = Button(window, text="This is Button widget", fg='blue')
btn.place(x=80, y=100)
btn.bind('<Button-1>', cpuTemp)
#label
lbl = Label(window , text='hi' , fg = "#0009ff0fc")
lblPlace = [ screen_width/2 , screen_height/2]
lbl.place(x=f'{lblPlace[0]}', y=f'{lblPlace[1]}')
window.mainloop()
# temp
this is not working can anyone fix this for me I would appreciate that.
it stills print in my pycharm consloe so why is my window not responding.
i am using pycharm as you might know now.
and I want to make this code working .
i am a python newbie so pls help it would mean a lot to me...
window.after(1000 , cpuTemp(event)) immediately runs cpuTemp(event) and passes the result to window.after. This creates an infinite loop since each call results in another call to the function.
The code needs to look something like this:
window.after(1000, cpuTemp, None)
The reason for None is that the function doesn't use the event, and the current event is relatively useless except for when the original event is being processed.

How do i get the key press and write it to a variable?

I am writing a program "translator". Wrote a programming interface. I want to make it so that I get what the user enters, write to a variable, translate and output.
However I don’t understand how to do it. I have looked at many forums but have not found an answer.
I want the user to enter his text for translation in the left text entry window, I receive this text, write it to a variable, translate and display the translated text in the right window. I want to do this in order to automate the program, so that the translation is automatic, without buttons.
`
from languages import lang
from function import *
from tkinter import *
from tkinter import ttk
import keyboard
from tkinter import messagebox
import googletrans
from googletrans import Translator
root = Tk()
app_width = 800
app_height = 500
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
x = (screen_width / 2) - (app_width / 2)
y = (screen_height / 2) - (app_height / 2)
root.title('Переводчик')
root['bg'] = '#1D1B26'
root.geometry(f'{app_width}x{app_height}+{int(x)}+{int(y)}')
root.resizable(width=False, height=False)
style = ttk.Style()
style.configure('TCombobox', pady=15 )
language_selection1 = ttk.Combobox(root, values = lang, font="Comfortaa 10", )
language_selection1.current(1)
language_selection1.place(relx=0.16,y=50)
language_selection1.bind("<FocusIn>", defocus)
exchange_button = PhotoImage(file='transfer.png')
img_label = Label(image=exchange_button)
exchange_button = exchange_button.subsample(18,18)
exchange_button1 = Button(root, image=exchange_button,background='#2ee59d',borderwidth=0, command=exchange_button)
exchange_button1.place(relx=0.49,y=50)
language_selection2 = ttk.Combobox(root, values = lang, font="Comfortaa 10", )
language_selection2.set("Выберите язык")
language_selection2.place(relx=0.66,y=50)
language_selection2.bind("<FocusIn>", defocus)
first_frame = Frame(root, bg="Black")
first_frame.place(x=41, y=100,width= 250, height=200) #127
text1 = Text(first_frame, bg = "White")
text1.place(x=0,y=0,width= 250, height=200)
label2 = Label(root)
second_frame = Frame(root, bg="Black")
second_frame.place(x=528, y=100,width= 250, height=200) #441
text2 = Text(second_frame, bg = "White")
text2.place(x=0,y=0,width= 250, height=200)
root.mainloop()
/function
def defocus(event):
event.widget.master.focus_set()
def exchange_button():
pass
/languages
lang = ['Belarusian',
'English',
'German',
'Italian',
'Japanese',
'Kazakh',
'Kyrgyz',
'Norwegian',
'Polish',
'Russian',
'Spanish',
'Swedish',
'Turkish',
'Ukrainian', ]
`
I want to do this in order to automate the program, so that the translation is automatic, without buttons.
Something has to trigger the translation, but it's not clear what you want that trigger to be. For this answer, I'll assume you want it to happen when the user presses the return key.
First, you need to write a function that does the translation. Since we're going to call this from an event, it needs to take an argument representing the event that triggered the function even though we don't need this argument in the function:
def do_translation(event):
source_lang = language_selection1.get()
target_lang = language_selection2.get()
text = text1.get("1.0", "end").strip()
translated_text = <your code to do the translation>
text2.delete("1.0", "end")
text2.insert("end", translated_text)
Next, instruct tkinter to call this function when the user presses the return key by binding the return key to the function:
text1.bind("<Return>", do_translation)
If you want the translation to happen as the user types, you can bind on the event <Any-KeyRelease> which will cause the function every time the user presses and releases a key:
text1.bind("<Any-KeyRelease>", do_translation)

Tkinter ValueError when converting seconds to minutes?

So, I'm working on a timer using Python and Tkinter's GUI. To do so, I intend to convert the minutes into seconds (as seen in my code) and use Python's time.sleep command to count down (not yet implemented).
from tkinter import *
import time
countdown = Tk()
countdown.geometry('500x300')
minute = Text(countdown, height = 0.01, width = 5)
minute.place(x=100, y=100)
minlabel = Label(text = "Input Minutes", font = ("MS Sans Serif", 10), bg = 'Light Blue')
minlabel.place(x=85, y = 80)
def go(event):
minseconds = int(minute.get("1.0", END))*60
print(int(minseconds))
countdown.bind('<Return>', go)
countdown.mainloop()
However, when I convert it to minutes, it works the first time (I.E, when I input 3, 180 returns), but any time after that I get this:
ValueError: invalid literal for int() with base 10: '3\n3\n\n'
Any idea what could be causing this? And why it works the first time but then stops working? Thanks :)
The problem is every time Enter is pressed a newline character is entered into the Text widget named minute and they mess up the conversion to int.
The simplest way I can think of to avoid that would be to just clear the widget in the event handler function:
def go(event):
minseconds = int(minute.get("1.0", END))*60
print(int(minseconds))
minute.delete('1.0', END) # <---- ADDED.
so actually the error is quite simple. You created a Text widget, which is just adding lines when you press Enter (corresponding to the \n characters). Just make your text widget bigger (instead of height = 0.01 maybe 2) and you will see it.
To do it more elegantly, you might try Entry() instead of Text(). See the example.
import time
import tkinter as tk
def go(event):
minseconds = int(min_entry.get())
seconds = minseconds*60
print(int(seconds))
countdown = tk.Tk()
countdown.geometry('500x300')
minlabel = tk.Label(text = "Input Minutes", font = ("MS Sans Serif", 10), bg = 'Light Blue')
minlabel.place(x=85, y = 80)
min_entry = tk.Entry()
min_entry.place(x=100, y=100)
countdown.bind('<Return>', go)
countdown.mainloop()
Furthermore try to put your functions always on top of your code, as they have to be defined before you call them. This might be causing trouble as you code gets bigger.
Hope you get a better understanding from tkinter by this :)
Check this update function. Import the module at top
import messagebox as msg
def go(event):
try:
minseconds = int(minute.get("1.0", END))*60
print(int(minseconds))
minute.delete("1.0", END)
except Exception:
msg.showerror("Error","invalid input provided.")
minute.delete("1.0", END)
But I would suggest to go with Entry With a StringVar()
from tkinter import *
from tkinter import messagebox as msg
countdown = Tk()
countdown.geometry('500x300')
minute=StringVar()
minut = Entry(countdown,textvariable=minute, width = 5)
minut.place(x=100, y=100)
minlabel = Label(text = "Input Minutes", font = ("MS Sans Serif", 10), bg = 'Light Blue')
minlabel.place(x=85, y = 80)
def go(event):
try:
minseconds = int(minute.get())*60
print(int(minseconds))
minute.set("")
except ValueError:
msg.showerror("Error","Invalid input provided.")
countdown.bind('<Return>', go)
countdown.mainloop()

Tkinter is there a way to resize the scroll bar in a canvas window

I have made most of this window already, and would prefer to not have to restart because of a hitch with a scrollbar not resizing properly. Problem being that the scrollbars appear way too small for the listboxes and I want them to span the whole height of each box respecitvely, but as of now they can only function if you spam the arrows as the actual scrolling bit can't move for lack of space. Any help would be appreciated, stuck on this for a while now. (Using python 3.8).
import tkinter as tk
from tkinter import *
setup = tk.Tk()
setup.title("Set Up Game")
setup.geometry("450x650")
setup.resizable(width=False, height=False)
select_Box = tk.Canvas(setup, width=450, height=496, bg="#cd3636")
select_Box.pack(padx=10)
listbox1 = Listbox(setup, width=33, height=30)
listbox1_win = select_Box.create_window(110,250, window=listbox1)
listbox2 = Listbox(setup, width=33, height=30)
listbox2_win = select_Box.create_window(320,250, window=listbox2)
scroll1 = Scrollbar(setup)
scroll1_win = select_Box.create_window(200,250, window=scroll1)
scroll2 = Scrollbar(setup)
scroll2_win = select_Box.create_window(410,250, window=scroll2)
listbox1.config(yscrollcommand = scroll1.set, selectmode=SINGLE)
scroll1.config(command = listbox1.yview)
listbox2.config(yscrollcommand = scroll2.set, selectmode=SINGLE)
scroll2.config(command = listbox2.yview)
nameArray = ["Bulbasaur", "Ivysaur", "Venasaur", "Charmander", "Charmelion", "Charazard", "Squirtle", "Wartortle", "Blastoise", "Lucario", "Garchomp", "Gengar", "Snorlax", "Reuniclus", "Joel","placeholder","placeholder","placeholder","placeholder","placeholder","placeholder","placeholder","placeholder","placeholder","placeholder","placeholder","placeholder","placeholder","placeholder","placeholder","placeholder","placeholder","placeholder","placeholder","placeholder","placeholder","placeholder","placeholder","placeholder","placeholder","placeholder","placeholder","placeholder","placeholder","placeholder","placeholder","placeholder","placeholder","placeholder","placeholder","placeholder","placeholder","placeholder","placeholder","placeholder","placeholder","placeholder","placeholder","placeholder","placeholder"]
for item in nameArray:
listbox1.insert(END, item)
setup.mainloop()
If you want to use Canvas.create_window to place all of your widgets, all you have to do is define the height of your scrollbar (you may need to play around with the numbers a little to get it to the right size).
So the edited snippet from your code will be:
scroll1 = Scrollbar(setup)
scroll1_win = select_Box.create_window(200,
250,
height=480, # this is all you're missing!
window=scroll1)

Python/Tkinter background not changing colours when configured to

I am trying to create a harmless prank joke on my friends, and I want the background of a python tkinter window(not canvas) to change to a random colour every second, then, after ten rounds, it will destroy itself. The problem is that when root.config(background=random_colour)is called, it will not change it's background colour. The entire code is below:
from tkinter import *
import pyglet
import time
import random
root = Tk()
text = Label( padx = 1000, pady = 999, text = 'VIRUS!' )
text.pack()
text.config(font=('Courier', 44))
root.attributes("-fullscreen", True)
root.update()
I'm cutting this bit out because it's just a list of all the named colours in python(It's called COLOURS).
for x in range(0, 9):
colours_length = len(COLOURS)
number = random.randint(0, colours_length)
random_colour = COLOURS[number]
root.config(background=random_colour)
time.sleep(1)
root.update()
root.destroy()
I've took acw1668's advice from the comments section, and it works now. Turns out that the label was covering the entire root window, and that was why it wasn't working.

Categories

Resources