I want to make a program that show me the divisors of the number introduced in a text box using python tkinter GUI and store the results into a plain text file.
I don't how to get the value from the text box. I understood that is something linked with get() , I read something but I still don't get it.
Here is the code:
from tkinter import *
def create_file():
file_object = open("C:/Users/valis/Desktop/Divisors.txt","w+")
def evaluate():
show_after= Label(text= "Check your Desktop !")
show_after.pack(pady=2, anchor=SW)
create_file()
#Windows size and Title
window = Tk()
window.title("Show Divisors")
window.geometry("300x100")
message = Label(window, text="Enter a number : ")
message.pack(pady=2, anchor=NW)
textbox_input = Text(window,height=1, width=11)
textbox_input.pack(padx= 2,pady= 2, anchor=NW)
window.mainloop()
The code isn't complete, so what should I do ?
As you said, you will use the get() function but with some additional attributes.
If we have a text box textbox_input, then you can return its input using this line:
test_input = textbox_input.get("1.0",END)
The first part, "1.0" means that the input should be read from line one, character zero (ie: the very first character). END is an imported constant which is set to the string "end". The END part means to read until the end of the text box is reached.
Reference: This answer.
Related
Why does the search fail when taking a string from a tk-inter text box?
The search works fine if I define the keyword as a string.
Minimal example:
import tkinter as tk
root = tk.Tk()
string="banana\napplepie\napple\n"
def searchcall():
textboxcontent=textExample.get("1.0","end")
keyword=filterbox.get("1.0","end")
keyword="apple" # search works as expected
print("keyword",keyword)
print("is keyword in textbox",keyword in textboxcontent)
for elem in textboxcontent.split():
print("seaching for",keyword,"in",elem,keyword in elem)
textExample=tk.Text(root, height=10)
textExample.insert(1.0,string)
textExample.pack()
filterbox=tk.Text(root, height=1)
filterbox.insert(1.0,"apple")
filterbox.pack()
btnRead=tk.Button(root, height=1, width=11, text="search",
command=searchcall)
btnRead.pack()
root.mainloop()
The problem is that tk inter appends a line break "\n" at the end when you read the contents of a widget.
Remove the "\n" at the end of the strings. For example, with strip
keyword=filterbox.get("1.0","end").strip()
you can also choose to read everything but the last character like this (source):
keyword=filterbox.get("1.0",'end-1c')
def move(sp, t):
if sp == "eightA":
sps = eightA
if t == "sixA":
st = sixA
if st == " ":
# target is empty
sps["text"] = " "
st["text"] = str(sps["text"])
Hello Everyone, Im trying to make this function to "move" text from a tkinter button to another, lets say sp is what i want to move, and t is the target so i want to move text
from the button eightA to sixA, also note that i want to be able to use this function on any 2 buttons, Its hard to explain, but please help if you can, the code above is one i tried out of alot other which didnt work,
Thanks
Procedure
Store the text on first button in a variable
Configure first button to have no text
Configure second button to have text stored in variable
Example
btn1 = tk.Button(text="Hello")
btn2 = tk.Button(text="Not Hello")
# store text on btn1 in a variable
txt = btn1['text']
# configure btn1 to have no text
btn1.config(text="")
# configure btn2 to have text stored in variable
btn2.config(text=txt)
So your function would look like
def move(btn1, btn2):
txt = btn1['text']
btn1.config(text=" ")
btn2.config(text=txt)
I have a script that continuously updates numbers on a text file in the same directory. I made a GUI using tkinter to display these numbers. I'm having a hard time getting the GUI to update the numbers in real time. It will display the numbers as they were when the GUI first started, but will not update the display as the text file changes. Here's some basic code to demonstrate:
def read_files(file, line):
old = open(f'{file}.txt', 'r').readlines()[line]
new = old.replace('\n', '')
return new
number = read_files('Statistics', 0)
number_label = Label(frame1, text=f'{number}')
number_label.grid(row=0, column=0)
The above code shows the number from the text file as it was when the GUI first opened. However, it does not update the number as its value in the text file changes. I did some reading around and also tried the following:
def read_files(file, line):
old = open(f'{file}.txt', 'r').readlines()[line]
new = old.replace('\n', '')
return new
number = read_files('Statistics', 0)
number_label = StringVar()
number_label.set(number)
number_display = Label(frame1, text=f'{number_label.get()}')
number_display.grid(row=0, column=0)
This has the same effect. It shows the value retrieved from the text file at the moment the GUI was opened, but does not update it as the text file is updated. Any help is appreciated.
Since there is no complete code, take a look at this example:
from tkinter import *
root = Tk()
def update_gui():
number = read_files('Statistics', 0) # Call the function
number_display.config(text=number) # Change the text of the label, also same as text=f'{number}'
root.after(1000,update_gui) # Repeat this function every 1 second
def read_files(file, line):
old = open(f'{file}.txt', 'r').readlines()[line]
new = old.replace('\n', '')
return new
number_display = Label(root) # Empty label to update text later
number_display.grid(row=0, column=0)
update_gui() # Initial call to the function
root.mainloop()
Here the label is created outside the function but the text is not given, but inside the function we are repeating the function every 1 second, with after, and changing the text of the label with config method. I have avoided the use of StringVar() as it's of no use here, you can just store it in a normal variable and use it.
Here is a plagiarized look at how after should be used:
def after(self, ms, func=None, *args):
"""Call function once after given time.
MS specifies the time in milliseconds. FUNC gives the
function which shall be called. Additional parameters
are given as parameters to the function call. Return
identifier to cancel scheduling with after_cancel."""
the code might be a little non-standart / messy. it's basically a guess the number game..
Any way, i want to change the label after the user pressing the yes/no button. i had some ideas but non of them worked well.. please help me :)
currently the label is "start from last time?" and i would like to change it to "choose a number between 1 - 99".
label = Label(root, text="start from last time?")
label.pack()
this is the function that activates when the user pressing the button, you can ignore what is written there just add the code :)
def yes():
fd = open("save.txt", "r")
data = fd.read()
data = data.split("|")
global answer
answer = int(data[0])
global attempts
attempts = int(data[1])
fd.close()
btnYes.pack_forget()
btnNo.pack_forget()
entryWindow.pack()
btnCheck.pack()
btnQuit.pack()
btnSave.pack()
root.geometry("500x150")
text.set("You Have {0} attempts Remaining! Good Luck!".format(attempts))
If what you are trying to do is to change the tk.Label text there are two ways to do it.
Label.config(text="Whaterver you want")
or
Label["text"] = "New Text"
I just started to learn Python and I'm trying to create a mineral counter by only using letters for microscopic petrography, but I am having problems passing my python code to Tkinker. Can you guys give tips about how to get my output to work? I'm finding it challenging to use theget() method even with online tutorials.
Can you guys teach this noob? Thank you!
My original code:
# define sample
sample = "qreqqwer"
# mineral q:
mineralq= "q"
countq = sample.count(mineralq)
# print count of q
print("The quantity of q is: ", countq)
The structure I made with Tkinker:
from tkinter import *
import tkinter as tk
# Window
window=tk.Tk()
window.title("Mineral Counter")
window.geometry("800x1000")
window.configure(bg="#00090F")
inputUser=tk.Text(window,width=225,height=5,font=("Arial bold",12),wrap="word", bg="#00090F", fg="white")
inputUser.pack()
# define sample
# mineral q:
countq = inputUser.count("q")
# print count of q
output.insert(tk.INSERT,countq)
output=tk.Text(window,width=20,height=2,font=("Arial bold",12), bg="#00090F", fg="white")
output.pack()
window.mainloop()
You need a button to update your code, becuase initially the Text boxes are empty and hence there is no occurence for q so nothing can be inserted.
Try this out:
First create a button with a function to click onto after the data is entered
b = tk.Button(window, text='Click Me', command=click)
b.pack()
Then now define the function that the button calls when is clicked onto
def click():
sample = inputUser.get('1.0', 'end-1c') #getting value from text box 1
mineralq = 'q' #letter to be counted
countq = sample.count(mineralq) #counting the letter
output.insert('1.0', f'The quantity of q is: {countq}') #inserting the output to text box 2
Hope it cleared your doubt, if any errors do let me know
Cheers