Insert text into python tkinter text widget - python

I have been making a program that responds to a user input. When I run it my code doesn't insert the response into the text widget. I get the error:
TypeError: insert() missing 1 required positional argument: 'chars'
My code is:
global stuff
stuff = open("Dictionary.txt", "r")
global contents
contents = stuff.read()
stuff.close()
from tkinter import *
dictionary = {"chungus": "Come at me chungus ... you wanna go?",
"hi": "It's good to see you!", "bot": "No - you're the BOT"}
def output():
TT = entry.get()
text.delete(0.0, END)
try:
meaning = dictionary[TT]
except:
meaning = "We do not have a reply for this yet..."
text.insert(meaning)
def words():
TT = (contents)
text.delete(0.0, END)
meaning = (TT)
text.insert(END, meaning)
global window
window = Tk()
window.title("WFR")
label1 = Label(window, text="Enter stuff for reply (No caps): ")
label1.grid(row=0, column=0, sticky=W)
entry = Entry(window, width=35, bg="light green")
entry.grid(row=1, column=0, sticky=W)
button1 = Button(window, text="SUBMIT", width=8, command=output)
button1.grid(row=3, column=0, sticky=W)
text = Text(window, width=60, height=20, wrap=WORD, background="yellow")
text.grid(row=2, column=0, sticky=W)
menubar = Menu(window)
firstmenu = Menu(menubar, tearoff=0)
firstmenu.add_command(label="Type What?", command=words)
menubar.add_cascade(label="Options", menu=firstmenu)
window.config(menu=menubar)
window.mainloop()
Have I missed something?

This is something quite simple to answer. In your code you have written text.insert(END, meaning), earlier in a different area you have typed text.insert(meaning). I think this is simply you missing something as you type your code. Try to copy the correct version of code (with the END, before it) in the line where you are getting your issue. Also, may I suggest adding comments to your code as it makes it a lot easier to see where the issue is.

Related

How to set time.sleep for different widgets

There is code that checks the availability of sites.
How can we make the status for each site to change at a user defined time (i.e. the time for each site can be different) The problem is that the number of sites is not limited, because you can add more lines to the application, so I do not understand how to implement it.
I attach a picture of how it looks like:
Code:
import tkinter as tk
from tkinter import ttk
import requests
import time
from tkinter import *
from tkinter import messagebox
data_list = []
window = Tk()
window.geometry('400x700')
window.title("SiteChecker")
def set_input(obj, value):
obj.delete(1.0, "END")
obj.insert("END", value)
def SiteCheck():
# time.sleep
for data in data_list:
url = data[0].get()
status = data[2]
if not str(url).startswith('http'):
continue
print(url)
Get_Response = None
try:
Get_Response = requests.get(url)
except:
status.config(text='status bad')
continue
if Get_Response.status_code == 200:
status.config(text='status ok')
pass
implement
else:
status.config(text='status bad')
def clicked():
txt = Entry(window, width=18)
txt.grid(column=0, pady=8)
txt_row = txt.grid_info()['row']
tim = Entry(window, width=3)
tim.grid(row=txt_row, column=1, pady=8)
txt_row = tim.grid_info()['row']
result1 = Label(window, text="status")
result1.grid(row=txt_row, column=2, pady=8)
data_list.append([txt, tim, result1])
lbl1 = Label(window, text="Enter references:")
lbl1.grid(column=0, row=1)
lbl2 = Label(window, text="Enter the test time: ")
lbl2.grid(column=1, row=1)
lbl3 = Label(window, text="Availability status ")
lbl3.grid(column=2, row=1)
for loop in range(2, 6):
txt1 = Entry(window, width=18)
txt1.grid(column=0, row=loop, pady=8)
tim1 = Entry(window, width=3)
tim1.grid(column=1, row=loop, pady=8)
result1 = Label(window, text="status")
result1.grid(column=2, row=loop, pady=8)
data_list.append([txt1, tim1, result1])
btn = Button(window, text="Add another site", command=clicked)
btn.grid(column=1, row=0)
Check_Button = Button(
window,
command=SiteCheck,
text='Start checking',
)
Check_Button.grid(row=0, column=2)
window.mainloop()
See here (How do I make my function run every second) how to use tkinter after() to achieve what you want. time.sleep won't work for your purpose because it is blocking the execution of the entire code.
From the link given in the comment to your question by Patrick Artner :
Tkinter root windows have a method called after() which can be used to schedule a function to be called after a given period of time. If that function itself calls after() you've set up an automatically recurring event.

Copying text in tkinter from label or msgbeox

I been searching for methods to copy text to clipboard or copy the results from Tkinter gui but idk if there is a command or something
here is my code for now here the result comes in a messagebox can i copy it to clipboard
import tkinter.messagebox
import string
import random
def qs_msgbbox(): # qs_msgbbox
tkinter.messagebox.showinfo("Info", "For customer support or tip or rating contact:"
"dghaily725#gmail.com\npress the button for generated pass\nmsg will appear then copy\nthe generated password")
def gen_pass(k=9): # gen_pass
char = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!##$%^&*"
password = ''
for i in range(9):
password += random.choice(char)
tkinter.messagebox.showinfo("Password", password)
root = Tk()
root.title("Password Generator")
lbl1 = Label(root, text="Generate Password", bd=2, relief=SUNKEN, height=5, width=50, bg='black', fg='white')
lbl1.configure(font=(70))
lbl1.grid(row=0, column=2)
lbl2 = Label(root, text='For more information press the Question mark', bd=2, relief=SUNKEN, fg='red')
lbl2.configure(font=(70))
lbl2.grid(row=0, column=0, pady=10)
btn1 = Button(root, text='Press to Generate', height=5, width=50, bg='grey', command=gen_pass)
btn1.configure(font=(70))
btn1.grid(row=1, column=2, padx=460, pady=50)
btn2photo = PhotoImage(file='question.png')
btn2 = Button(root, image=btn2photo, width=30, height=30, command= qs_msgbbox)
btn2.grid(row=0, column=1)
root.mainloop()
and also just a quick small question is it better to use classes or this form
Tkinter does have a function for that, simply just
from tkinter import Tk
root = Tk()
root.clipboard_clear()
root.clipboard_append("Something to the clipboard")
root.update() # the text will stay there after the window is closed
Hope I could help
Greets
The above answer is perfectly fine. Infact its the method to do it. I read the comments, He had mentioned that it could only take in string. That is completely false. It can also take in functions. For example..
import tkinter as tk
root = tk.Tk()
#creating a entry Widget.(Labels are fine as well)
entry = tk.Entry(root)
entry.pack()
#NOW if you want to copy the whole string inside the above entry box after you
typed in #
def copy ():#assign this function to any button or any actions
root.clipboard_clear()
root.clipboard_append(entry.get()) #get anything from the entry widget.
root.mainloop()
Hoping this was helpful

Putting two buttons next to each other with Tkinter

I was coding a GUI with the Tkinter library in Python and I've ran into the following problem:
# DECLARATIONS
labelPresentation = Label(window, text="Insert here")
name = StringVar()
nameEntered = Entry(window, width=25, textvariable=name)
labelPresent = Label(window)
research = ttk.Button(window, text="Search", command=searchToPut)
elimination = ttk.Button(window, text="Delete", command=searchToDelete)
# POSITIONS
labelPresentation.grid(column=0, row=0)
nameEntered.grid(column=0, row=1)
labelPresent.grid(column=0, row=3)
research.grid(column=0, row=2)
elimination.grid(column=0, row=2)
I need to put the elimination and research button next to each other but the grid function is causing me problems, because this code put them one in top of the other. I searched for the same problem and they suggested to use the pack() function, but when I try it it says that I can't use both grid and pack function to place buttons and labels.
Thanks in advance for the help!
Try this:
# DECLARATIONS
labelPresentation = Label(window, text="Insert here")
name = StringVar()
nameEntered = Entry(window, width=25, textvariable=name)
labelPresent = Label(window)
research = ttk.Button(window, text="Search", command = searchToPut)
elimination = ttk.Button(window, text="Delete", command =searchToDelete )
# POSITIONS
#labelPresentation.grid( row=0)
labelPresentation.place(x=50)
nameEntered.place(x=0,y=20)
labelPresent.grid( row=0)
research.grid(row=2,column=0)
elimination.grid(row=2, column = 1 , padx=0,pady = 25)
Output:

Why isn't my label being displayed in tkinter?

def name_label_manager(event):
name = name_entry.get()
label_name = Label(root, text="Name: " + name)
label_name.grid(row=10, column=1, sticky=W)
label_name.delete(0, "end")
def description_label_manager(event):
description1 = description.get()
descrpt = Label(root, text="Description: " + description1)
descrpt.grid(row=9, column=1, sticky=W)
descrpt.delete(0, "end")
i am calling them like this:
button_get = Button(root, text="Submit")
button_get.bind("<Button-1>", description_label_manager,name_label_manager)
button_get.grid(row=2, column=8)
i dont know if this i right but i am calling them with button
for some reason the desctription_label_manager label will show, but the name label wont
As Bryan Oakley pointed out, labels do not have a delete method, Entry Listbox do, but not labels
More so, you can think of tkinter widgets as images drawn on your screen, for these images to display text they must have variables associated with them, here we create some StringVar() variables and assign them to the Entry which you can then use the get method to get what is currently stored in them.
You can add a command argument to a Button to call a function, that should do in this your case.
Check out the code below to understand what I just explained above
import tkinter as tk
def name_label_manager(event=None):
name = name_entry_variable.get()
label_name = tk.Label(root, text="Name: "+name)
label_name.grid(row=10, column=1)
#label_name.delete(0, "end")
description_label_manager()
def description_label_manager(event=None):
description1 = description_entry_variable.get()
descrpt = tk.Label(root, text="Description: "+description1)
descrpt.grid(row=9, column=1)
#descrpt.delete(0, "end")
root=tk.Tk()
name_entry_variable=tk.StringVar()
description_entry_variable=tk.StringVar()
name_entry=tk.Entry(root,textvariable=name_entry_variable,width=10)
name_entry.grid(row=2, column=8)
description_entry=tk.Entry(root,textvariable=description_entry_variable,width=10)
description_entry.grid(row=3, column=8)
button_get = tk.Button(root, text="Submit", command=name_label_manager)
#button_get.bind("<Button-1>", description_label_manager,name_label_manager) command argument of Button should do
button_get.grid(row=4, column=8)
root.mainloop()

Python GUI using Tkinter how to print input exactly the way you enter them?

I'm exploring tkinter as of now and trying to do sample exercises I can think of. What I want is when I enter an input like this:
I've
entered
this
I want to display them that way as well but I'm only getting this:
I'veenteredthis
This is a snippet from my code for this part:
input = textBox.get("1.0", 'end-1c')
logBox.insert(tk.END, input)
I've tried doing these:
input = input.replace("\n", "\n"), logBox.insert(tk.END, input+ "\n")
Please do understand that I'm not well equipped with knowledge in Python as I am still trying to learn the language. Thank you in advance!
Edit: Here is the full code just don't mind the other parts since I'm trying to do something
import sys
import os
import time
import operator
import tkinter as tk
from tkinter import *
def test():
input = textBox.get("1.0", 'end-1c')
# input = input.replace("\n", "\n")
logBox.insert(tk.END, input+ "\n")
window = tk.Tk()
window.geometry("{0}x{1}+0+0".format(window.winfo_screenwidth(),
window.winfo_screenheight()))
window.title("Test")
mainFrame = Frame(window, width=8000, height=8000)
mainFrame.pack(side=TOP)
LabelText = Label(mainFrame, text="Type your text below:", anchor='center', pady=10)
LabelText.pack()
textBox = tk.Text (mainFrame, font=('averdana', 10), height=18, width=180)
textBox.pack()
BTNRun = Button(mainFrame, text="Run", height=1, width=10,
command=test)
BTNRun.pack(padx=10, pady=10)
LogText = Label(mainFrame, text="Console Log", anchor='ne', pady=10)
LogText.pack()
logBox = tk.Listbox(mainFrame, font=('averdana', 10), height=10, width=180)
logBox.pack()
BTNExit = Button(mainFrame, text="Exit", height=1, width=10, command=quit)
BTNExit.pack()
window.mainloop()```
Do not name a variable input. input is a built in method of python. That said you need to split the string at the line breaks so use split() and then input the resulting list.
Change this:
def test():
input = textBox.get("1.0", 'end-1c')
# input = input.replace("\n", "\n")
logBox.insert(tk.END, input+ "\n")
To this:
# had to update this function my original answer had some issues
def test():
my_input = textBox.get("1.0", 'end-1c')
x = my_input.split("\n")
for item in x:
logBox.insert(tk.END, item.strip())

Categories

Resources