Tkinter StringVar shows random numbers instead of variable on label - python

The title says it all.
import tkinter as tk
from tkinter import filedialog, Text, StringVar
root = tk.Tk()
root.resizable(False, False)
var1 = StringVar()
topn = ""
print(topn)
def addApp():
global topn
topn = topn + "1"
print(topn)
var1.set(topn)
canvas = tk.Canvas(root, height=500, width=400, bg="#263D42")
canvas.pack()
frame = tk.Frame(root, bg="orange")
frame.place(relwidth=0.8, relheight=0.8, relx=0.1, rely=0.1)
Resultlabel = tk.Label(root,text=var1.get, padx=100, pady=5, fg="white", bg="grey")
Resultlabel.pack()
t
openFile = tk.Button(frame, text="Open File", padx=10, pady=5, fg="white", bg="#263D42", command=addApp)
openFile.pack()
root.mainloop()
[btw, ignore the Open File, i was following a tutorial to learn the basics of tkinter and then edited the code to fit my needs. I forgot to change the text in the button.]
https://i.stack.imgur.com/2FVKG.png

text is not the same thing as textvariable. text is used to associate static text with a widget, textvariable is used to have the text of the widget be synchronized with the value of a variable.
If you want ResultLabel to always show what is in var1 you must define it like this:
Resultlabel = tk.Label(root,textvariable=var1, padx=100, pady=5, fg="white", bg="grey")

Related

How to auto-wrap widget in tkinter?

I saw this function (layout?) in android a few years ago, but I can't remind what is this function name...
I need an auto-replace widget.
if the new widget' width meets the end of the window, I want to move that widget new line.
The below is my expected output.
I Think, get the width and calculate new widget position will solve it.
But, I think this is so common need. Does tkinter support it?
Since tkinter has a canvas which gives you absolute control over positioning, you can accomplish this with just a little bit of math when adding items. You'll have to add code to reposition the widgets when the window is resized.
A simpler approach is to use the text widget, which supports embedded images or widgets, and has support for wrapping.
Here's a demonstration:
import tkinter as tk
root = tk.Tk()
toolbar = tk.Frame(root)
text = tk.Text(root, wrap="word", yscrollcommand=lambda *args: vsb.set(*args))
vsb = tk.Scrollbar(root, command=text.yview)
toolbar.pack(side="top", fill="x")
vsb.pack(side="right", fill="y")
text.pack(side="left",fill="both", expand=True)
COUNT = 0
def add_widget():
global COUNT
COUNT += 1
widget = tk.Label(root, width=12, text=f"Widget #{COUNT}", bd=1, relief="raised",
bg="#5C9BD5", foreground="white", padx=4, pady=4)
text.configure(state="normal")
text.window_create("insert", window=widget, padx=10, pady=10)
text.configure(state="disabled")
add_button = tk.Button(toolbar, command=add_widget, text="Add")
add_button.pack(side="left")
for i in range(9):
add_widget()
root.mainloop()
Refactored code :
The code in Bryan's answer works very well! But a little bit difficult to understand.
Thus I refactor the code
import tkinter as tk
def add_widget():
widget = tk.Button(root, width=12, text=f"Widget", padx=4, pady=4)
text.window_create("end", window=widget, padx=10, pady=10)
root = tk.Tk()
add_button = tk.Button(root, command=add_widget, text="Add")
add_button.pack()
text = tk.Text(root, wrap="word", yscrollcommand=lambda *args: vscroll.set(*args))
text.configure(state="disabled")
text.pack(side="left",fill="both", expand=True)
vscroll = tk.Scrollbar(root, command=text.yview)
vscroll.pack(side="right", fill="both")
root.mainloop()

why doesnt my label appear in my tkinter window when i use the RAISED relief but does appear when i use another relief?

from tkinter import *
window = Tk()
window.geometry("300x300")
window.config(background="red")
window.title("label")
photo = PhotoImage(file='photo_1.png')
label = Label(window,
text="hello world",
font=('Arial',40,"bold"),
fg="black",
bg="yellow",
relief=RAISED,
bd=10,
padx=20,
pady=20,
image=photo,
compound='bottom')`
label.pack()
window.mainloop()
when i use the RAISED relief, my label doesnt appear in my tkinter window. but when i change it to SUNKEN or FLAT relieves, it does appear.

Why isn't this label changing when I use the tkinter config option

I want to change this label so I used the widget.config option but it's not working for some reason. Here's my code:
import tkinter as tk
root = tk.Tk()
root.attributes('-fullscreen', True)
exit_button = tk.Button(root, text="Exit", command = root.destroy)
exit_button.place(x=1506, y=0)
def answer():
global main_entry
answer_label.config(main_entry)
frame = tk.Frame(root)
main_entry = tk.Entry(frame, width=100)
main_entry.grid(row=0, column=0)
go_button = tk.Button(frame, text='Go!', width=85, command = answer)
go_button.grid(row=1, column=0)
answer_label = tk.Label(text = "Hey").pack()
frame.place(relx=.5, rely=.5, anchor='center')
root.mainloop()
While using the config function, you have to mention what is it that you want to change.
try:-
answer_label.config(text="Text that you want to be displayed")
Also you have not fetched the value from the Entry widget: For that, you can use:
answer_label.config(text=main_entry.get())
Full code will look like this:
import tkinter as tk
root = tk.Tk()
root.attributes('-fullscreen', True)
exit_button = tk.Button(root, text="Exit", command = root.destroy)
exit_button.place(x=1506, y=0)
def answer():
answer_label.config(text=main_entry.get())
frame = tk.Frame(root)
main_entry = tk.Entry(frame, width=100)
main_entry.grid(row=0, column=0)
go_button = tk.Button(frame, text='Go!', width=85, command = answer)
go_button.grid(row=1, column=0)
answer_label = tk.Label(text = "Hey")
answer_label.pack()
frame.place(relx=.5, rely=.5, anchor='center')
root.mainloop()
This code works. It configures the label to change the text. I don't know what you are trying to achieve with the config(main_entry).
import tkinter as tk
root = tk.Tk()
root.attributes('-fullscreen', True)
exit_button = tk.Button(root, text="Exit", command = root.destroy)
exit_button.place(x=1506, y=0)
def answer():
global main_entry, answer_label
answer_label.config(text="hi")
frame = tk.Frame(root)
main_entry = tk.Entry(frame, width=100)
main_entry.grid(row=0, column=0)
go_button = tk.Button(frame, text='Go!', width=85, command = answer)
go_button.grid(row=1, column=0)
answer_label = tk.Label(text = "Hey")
answer_label.pack()
frame.place(relx=.5, rely=.5, anchor='center')
root.mainloop()

How can i update a tkinter window with a new defined variable?

I want to create two windows with one button in the first one one and one label in the second.
When i press the button the label in the second window should refresh and display the variable plus 1.
I dont want to close the second window and re open it afterwards.
Any ideas how that could be done?
import tkinter as tk
text = 1
root = tk.Tk()
root2 = tk.Tk()
label = tk.Label(root, bg="green", text=text, fg="blue")
label.place(relx=0.1, rely=0.1, relheight=0.3, relwidth=0.3)
def plus():
global text
text = text + 1
print(text)
button = tk.Button(root2, bg="blue", text="Button", command=plus)
button.pack()
root.mainloop()
root2.mainloop()
This code should do the basics but the line to refresh the second window is still missing.
Hopefully anyone can tell me how to that :)
Use Toplevel() window instead of using Tk() as secondary windows. Tkinter is single threaded so using one mainloop() is sufficient for all the windows.
Now as you've asked that you want one button in one window and a label which updates in the second window, and also you can reopen the window without losing any progress if you close the second window.
Here is my way.
import tkinter as tk
text = 1
root = tk.Tk()
root2 = tk.Toplevel()
label = tk.Label(root2, bg="green", text=text, fg="blue")
label.place(relx=0.1, rely=0.1, relheight=0.3, relwidth=0.3)
def plus():
global text, root2, label
if not root2.winfo_exists(): # checks if the window is closed or not
root2 = tk.Toplevel()
label = tk.Label(root2, bg="green", text=text, fg="blue")
label.place(relx=0.1, rely=0.1, relheight=0.3, relwidth=0.3)
text += 1
label['text'] = text
button = tk.Button(root, bg="blue", text="Button", command=plus)
button.pack()
root.mainloop()
Using IntVar() to update all the label values. Can use StringVar() for sting type:
Sample
import tkinter as tk
root = tk.Tk()
root2 = tk.Toplevel()
# This is a textvariable IntVar can also use StringVar for sting input
text = tk.IntVar()
text.set(1) # Set the initial to 1
# Use 'textvariable' instad of text
label = tk.Label(root2, bg="green", textvariable=text, fg="blue")
label.place(relx=0.1, rely=0.1, relheight=0.3, relwidth=0.3)
label2 = tk.Label(root, textvariable=text)
label2.pack()
def plus():
global text, root2, label
if not root2.winfo_exists(): # checks if the window is closed or not
root2 = tk.Toplevel()
label = tk.Label(root2, bg="green", textvariable=text, fg="blue")
label.place(relx=0.1, rely=0.1, relheight=0.3, relwidth=0.3)
text.set( text.get()+1 ) # incrementing by 1 ( text.get() will return the value )
button = tk.Button(root, bg="blue", text="Button", command=plus)
button.pack()
root.mainloop()
I hope you may find something useful from my answer.
You can't run two mainloops in one thread. Your call to root.mainloop() blocks until you close the window. Once you close the window, it exits that method and runs root2.mainloop() because it's the next line of code.
One root pane can have multiple windows, you don't need to make a root2. You want to make two Toplevel windows
To expand upon the answer already given, you should use Toplevel rather than two root windows.
Also in order to change the text of the label you use label['text'] = str(text) to update the value.
import tkinter as tk
text = 1
root = tk.Tk()
root2 = tk.Toplevel()
def plus():
global text
text = text + 1
label['text'] = str(text)
label = tk.Label(root, bg="green", text=text, fg="blue")
label.place(relx=0.1, rely=0.1, relheight=0.3, relwidth=0.3)
button = tk.Button(root2, bg="blue", text="Button", command=plus)
button.pack()
root.mainloop()
If I've understand, try this, every time you open a window, toplevel, the label in the new window is increment by 1
import tkinter as tk
class Test(tk.Toplevel):
def __init__(self, parent, count):
super().__init__()
self.parent = parent
self.count = tk.IntVar()
self.count.set(count)
self.title("I'm a new toplevel.")
self.init_ui()
def init_ui(self):
self.label = tk.Label(self, textvariable=self.count).pack()
self.close_me = tk.Button(self, text= "Close me", command = self.on_close_me).pack()
self.close_parent = tk.Button(self, text= "Close parent", command = self.on_close_parent).pack()
def on_close_me(self):
self.destroy()
def on_close_parent(self):
self.parent.on_close()
class App(tk.Frame):
def __init__(self,):
super().__init__()
self.master.title("Hello World")
self.count =0
self.init_ui()
def init_ui(self):
self.pack(fill=tk.BOTH, expand=1,)
f = tk.Frame()
w = tk.Frame()
tk.Button(w, text="Open", command=self.callback).pack()
tk.Button(w, text="Close", command=self.on_close).pack()
f.pack(side=tk.LEFT, fill=tk.BOTH, expand=0)
w.pack(side=tk.RIGHT, fill=tk.BOTH, expand=0)
def callback(self):
self.count +=1
obj = Test(self,self.count)
def on_close(self,evt=None):
self.master.destroy()
if __name__ == '__main__':
app = App()
app.mainloop()

TKinter update scrolledText

On create window, tkinter.scrolledtext look up for SearchIP() to insert but never update layout. When I have different input for SearchIP() method never show up. It only shows the initial value.
Note: I added a couple of print statements to watch if SearchIP() returns the right thing, which is the case, for example for 'www.google.com' it prints '216.58.192.4', but this value never shows up in ScrolledText.
import socket
try:
# for Python2
import Tkinter as tk
import ScrolledText as tkst
except ImportError:
# for Python3
import tkinter as tk
import tkinter.scrolledtext as tkst
global Filename
root = tk.Tk()
frame = tk.Frame(root,width=100)
label = Label(root,text="http://")
label.grid(row=0,column=0)
entryVar = tk.StringVar()
entry = Entry(root,width=50,textvariable=entryVar)
entry.grid(row='0',column='1',columnspan=8)
def SearchIP():
print(entryVar.get())
add = str(entryVar.get())
ip_a = socket.gethostbyname(add)
print(str(ip_a))
return str(ip_a);
button1 = Button(root, text="Search IP", command=SearchIP)
button1.grid(row=1, column=0)
button2 = Button(root, text="DNS Recon")
button2.grid(row=1, column=1)
button3 = Button(root, text="Port Scanner")
button3.grid(row=1, column=2)
button4 = Button(root, text="Web Crawl")
button4.grid(row=1, column=3)
button5 = Button(root, text="Email Gathering")
button5.grid(row=1, column=4)
frame.grid(row=2, column=0, columnspan=30, rowspan=30)
edit_space = tkst.ScrolledText(
master = frame,
wrap = 'word', # wrap text at full words only
width = 45, # characters
height = 10, # text lines
# background color of edit area
)
# the padx/pady space will form a frame
edit_space.pack(fill='both', expand=True, padx=8, pady=8)
root.title("E-Z Security Audting")
root.resizable(True, True)
edit_space.insert('insert', SearchIP())
root.mainloop()
I also tried to modify the SearchIP() method and remove the return statement, but then I got this error:
File "C:/Users/kero/Desktop/Robert_HodgesKeroles_Hakeem_secproject/secproject/new‌​User_Interface.py", line 50, in <module>
edit_space.insert('insert', SearchIP())
File "C:\Python27\lib\lib-tk\Tkinter.py", line 2986, in insert
self.tk.call((self._w, 'insert', index, chars) + args)`
SearchIP after modification
def SearchIP():
add = str(entryVar.get())
ip_a= socket.gethostbyname(add)
You have to use insert() inside SearchIP()
import socket
try:
# for Python2
import Tkinter as tk
import ScrolledText as tkst
except ImportError:
# for Python3
import tkinter as tk
import tkinter.scrolledtext as tkst
# --- functions ---
def SearchIP():
add = entryVar.get()
ip_a = socket.gethostbyname(add)
edit_space.insert('insert', ip_a + "\n")
# --- main ---
root = tk.Tk()
root.title("E-Z Security Audting")
root.resizable(True, True)
frame = tk.Frame(root, width=100)
frame.grid(row=2, column=0, columnspan=30, rowspan=30)
label = tk.Label(root, text="http://")
label.grid(row=0, column=0)
entryVar = tk.StringVar()
entry = tk.Entry(root, width=50, textvariable=entryVar)
entry.grid(row=0, column=1, columnspan=8)
button1 = tk.Button(root, text="Search IP", command=SearchIP)
button1.grid(row=1, column=0)
button2 = tk.Button(root, text="DNS Recon")
button2.grid(row=1, column=1)
button3 = tk.Button(root, text="Port Scanner")
button3.grid(row=1, column=2)
button4 = tk.Button(root, text="Web Crawl")
button4.grid(row=1, column=3)
button5 = tk.Button(root, text="Email Gathering")
button5.grid(row=1, column=4)
edit_space = tkst.ScrolledText(
master=frame,
wrap='word', # wrap text at full words only
width=45, # characters
height=10, # text lines
# background color of edit area
)
edit_space.pack(fill='both', expand=True, padx=8, pady=8)
root.mainloop()

Categories

Resources