can we code time in text widget? - python

Is it possible to code time HH:MM:SS using text widget?
I know we can do this with label widget. My code deals with text widget and want to display time at any corner on the TKinter window.
If possible how to delete and insert the text using label widgets. Text widget has the following methods default.
delete(startindex [,endindex])
This method deletes a specific character or a range of text.
insert(index [,string]...)
This method inserts strings at the specified index location.
In my code the text has to be deleted and inserted all the time.
thanks.

delete from 1.0 to end.
import datetime
text.delete('1.0', 'end')
text.insert('end', datetime.datetime.now().strftime('%H:%M:%S')) # text.insert('end', label['text'])
label['text'] = datetime.datetime.now().strftime('%H:%M:%S')
Display Entry on bottom right
import datetime
from Tkinter import * # from tkinter import * # Python 3.x
root = Tk()
root.geometry('500x500')
frame = Frame(root)
frame.pack(side=BOTTOM, fill=BOTH)
entry = Entry(frame)
entry.pack(side=RIGHT)
entry.insert(END, datetime.datetime.now().strftime('%H:%M:%S'))
root.mainloop()
def __init__(self):
tk.Tk.__init__(self)
self.geometry("1360x750")
frameLabel = tk.Frame(self)
self.text = tk.Text(frameLabel)
frameLabel.pack(side=BOTTOM, fill=BOTH)
self.text.pack(side=RIGHT)
self.text.insert('end', 'TEST')
self.queue = Queue.Queue()
thread = SerialThread(self.queue)
thread.start()
self.process_serial()
UPDATE2
import datetime
from Tkinter import * # from tkinter import * # Python 3.x
root = Tk()
root.geometry('500x500')
frame = Frame(root)
frame.pack(side=BOTTOM, fill=BOTH)
label = Label(frame)
label.pack(side=RIGHT)
label['text'] = datetime.datetime.now().strftime('%H:%M:%S')
root.mainloop()

Related

Tkinter label grid_propagate doesn't work

I'm trying to ad a label to a tkinter app, showing the procedure status, while doing something.
I don't want my window to stretch to follow the label size, so I used grid_propagate to apply this flag to the label and it's master, but this seems like is not working and the grid is moving, following the label size.
Here an example, following the same structure of my original program:
from tkinter import *
from tkinter import ttk
import threading
import time
def buttonManage():
label1.grid(columnspan=2, sticky=W)
threading.Thread(target=labelManage, name='LabelThread').start()
def labelManage():
while not label1.winfo_ismapped():
# Wait for graphic interface manager to draw, before removing resizing propagation from container frame
time.sleep(0.1)
label1.master.grid_propagate(False)
label1.grid_propagate(False)
for n in range(1, 100):
label1.configure(text=label1.cget('text') + 'a')
time.sleep(0.1)
label1.master.grid_propagate(True)
label1.grid_propagate(True)
window = Tk()
window.resizable(False, False)
tabControl = ttk.Notebook(window)
mainFrame = ttk.Frame(tabControl, padding='10 10 10 10')
optionFrame = ttk.Frame(tabControl, padding='10 10 10 10')
tabControl.add(mainFrame, text ='Backup')
tabControl.add(optionFrame, text ='Options')
tabControl.grid()
button = ttk.Button(mainFrame, text='Backup', command=buttonManage)
button.grid(columnspan=2, ipadx=70, ipady=20)
label1 = ttk.Label(mainFrame, text='')
window.mainloop()

How to close the empty tkinter window that pops up when I run my code

I am trying to create a tkinter gui that performs a certain calculation. I create a window to ask for input to do the calculations. However, each time I run my code 2 windows pop up instead of one. Is there a way to automatically close the blank window when I run my code such that the user would only see the window that asks for input.
For simplicity I changed all buttons to close the applications.
import numpy as np
import pandas as pd
from datetime import datetime
import tkinter as tk
import tkinter.ttk as ttk
import tkinter.messagebox
import blpapi
import pdblp
con = pdblp.BCon(timeout=5000)
con.start()
s= ttk.Style()
s.theme_use('xpnative')
root =tk.Tk()
root.title("Vega Requirement Application")
root.geometry("600x400")
ticker_var= tk.StringVar()
volume_var= tk.StringVar()
def close():
root.destroy()
def clear_all():
root.destroy()
def vega_calculation():
root.destroy()
ticker_label = ttk.Label(root, text='Bloomberg Ticker:',font=('calibre',10,'normal'))
ticker_entry = ttk.Entry(root, textvariable = ticker_var,font=('calibre',10,'normal'))
volume_label = ttk.Label(root, text='Volume:',font=('calibre',10,'normal'))
volume_entry = ttk.Entry(root, textvariable = volume_var,font=('calibre',10,'normal'))
run_btn = ttk.Button(root, text = 'Calculate', command = vega_calculation, width = 13)
close_btn = ttk.Button(root, text= 'Close App', command = close, width =13)
clear_btn = ttk.Button(root, text= 'Clear table', command = clear_all, width=13)
ticker_label.grid(row=0,column=0)
ticker_entry.grid(row=0,column=1)
volume_label.grid(row=1,column=0)
volume_entry.grid(row=1,column=1)
run_btn.grid(row=0,column=2)
close_btn.grid(row=1, column=2)
clear_btn.grid(row=0, column =4)
root.mainloop()
The following two lines will create an instance of Tk() because there is no instance of Tk() when they are executed:
s = ttk.Style() # create an instance of Tk() if there is none
s.theme_use('xpnative')
Move the two lines to after root = tk.Tk() so that it uses the already created instance of Tk():
root = tk.Tk()
s = ttk.Style() # use existing instance of Tk(), root
s.theme_use('xpnative')

How to add padding before element name in tkinter listbox or remove underline under selected item?

When inserting elements in listbox I want to add a little padding to their right. For example:
import tkinter as tk
from tkinter import *
root = Tk()
listbox = Listbox(root,width = 50)
listbox.pack(side=LEFT,fill=Y)
for ele in range(1,10):
listbox.insert(END,str(ele))
root.mainloop()
Gives:
I want something like this:
import tkinter as tk
from tkinter import *
root = Tk()
listbox = Listbox(root,width = 50)
listbox.pack(side=LEFT,fill=Y)
for ele in range(1,10):
listbox.insert(END," "+str(ele))
root.mainloop()
Now, I am looking for an in-build way of doing this because I need add extra code to remove those spaces when I do listbox.get(listbox.curselection()). Or for a way to remove the underline under the selected item so that the user can't see my dirty quick fix.
Place your Listbox in a Frame with ipadx.
LiveDemo: reply.it
Reference
The Tkinter Pack Geometry Manager - options
import tkinter as tk
class App(tk.Tk):
def __init__(self):
super().__init__()
self.geometry('600x300+50+50')
self.configure(bg='blue')
frame = tk.Frame(self, bg='white')
frame.pack(side=tk.LEFT, ipadx=10)
listbox = tk.Listbox(frame, borderwidth=0, highlightthickness=0, bg=frame.cget('bg'), width=50)
listbox.pack(fill=tk.Y)
for ele in range(1,10):
listbox.insert(tk.END, str(ele))
if __name__ == '__main__':
App().mainloop()

Python prints numbers instead of words

I'm trying to make a Tkinter program that displays what you enter but instead I get a bunch of numbers in the IDLE shell.
My program:
from Tkinter import *
class App:
def __init__(self, master):
frame = Frame(master)
frame.pack()
self.text_write = Entry(frame)
self.text_write.pack()
self.Show = Button(frame, text='Show', command=self.Show)
self.Show.pack(side=RIGHT)
def Show(self):
Label(self.text_write.get())
root = Tk()
app = App(root)
root.mainloop()
but instead of text being shown. Numbers appear in my IDLE shell such as:
.4334975024
.4334975600
.4334975672
.4334975816
.4334975960
.4334976104
.4334976248
.4334976392
.4334976536
would somebody please explain the problem and how I could fix it.
def Show(self):
Label(self.text_write.get())
If you replace "Label" with "print" it works (as in, prints the value to stdout)
What the code does as-is is create a new label with a string as a parent (when it wants a window as a parent), and then doesn't attach that label to anything.
You probably want to create the Label object and attach it to the window in init, and then update the label's value in Show()?
Try this:
from Tkinter import *
class App:
def __init__(self, master):
frame = Frame(master)
frame.pack()
self.text_write = Entry(frame)
self.text_write.pack()
# rename the show button because you gave a member function the same name
self.show_button = Button(frame, text='Show', command=self.Show)
self.show_button.pack(side=RIGHT)
# create label to display entered text
self.display = Label(frame, text='')
self.display.pack(side=BOTTOM)
def Show(self):
# print text to the standard output
print self.text_write.get()
# show text on label
self.display['text'] = self.text_write.get()
root = Tk()
app = App(root)
root.mainloop()

Random number in label in python 3 and tkinter

How can I make that in label generate some numbers for example:
some text(e.g.Input): #here generate numbers#
Input and Output are text in label
I want to make that number are generated every second in the label
To wait one second between each random number, use the after method and change the text in the scheduled function:
from tkinter import Tk, Label
import random
root = Tk()
label = Label(root)
label.pack()
def replace_text():
label.config(text=str(random.random()))
root.after(1000, replace_text)
replace_text()
root.mainloop()
Is this what you're looking for?
Every time you press the button, a new random number is displayed.
import tkinter as tk
import random
class Window:
def __init__(self, master):
self.frame = tk.Frame(master)
self.text = tk.StringVar()
self.text.set(random.randint(1, 10))
self.ranNumLabel = tk.Label(self.frame, textvariable = self.text)
self.genButton = tk.Button(self.frame, text = 'Generate Random Number', command = self.genRanNum)
self.ranNumLabel.grid(row = 0)
self.genButton.grid(row = 1)
self.frame.grid()
def genRanNum(self):
self.text.set(random.randint(1, 10))
# when text is updated, the Label associated with it also updated
def main():
root = tk.Tk(className = ' Random Number Generator')
app = Window(root)
root.mainloop()
if __name__ == '__main__':
main()
Your question is rather confusing, but here is what I can answer...
To generate a random number use the random.random() function and the label() function in tkinter.
Here is an example:
import random
from tkinter import *
x=random.random()
root = Tk()
w = Label(root, text=x)
w.pack()
root.mainloop()

Categories

Resources