Text label not showing up - python

I have changed everything on other answers but nothing works.
from tkinter import *
import tkinter as tk
import tkinter
import pynput
from pynput.keyboard import Key, Listener
from tkinter import filedialog
charCount = 0
keys = []
press_value = 0
root = Tk()
my_menu = Menu(root)
root.config(menu=my_menu)
def label1(root):
label = tkinter.Label(root, text = "correct")
label.pack()
def pressOn():
button_1.configure(fg = "Green", text = "ON")
def pressOff():
button_1.configure(fg = "red", text = "OFF")
class Window(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.master = master
self.pack(fill=BOTH, expand=1)
def save_location():
location_window = Tk()
var = StringVar()
var.set('No Folder Selected')
locationLabel = Label(location_window, textvariable=var.get())
locationLabel.place(x=70,y=20)
location_window.update()
def browse_button():
filename = filedialog.askdirectory()
print(filename)
var = filename
button2 = Button(location_window, text="Browse", command=browse_button).grid(row=1, column=0)
location_window.title('Save Location')
location_window.iconbitmap('C:/Users/Gaming/Downloads/floppydisk.ico')
location_window.geometry('250x100')
location_window.mainloop()
file_menu = Menu(my_menu, tearoff=False)
my_menu.add_cascade(label="File", menu=file_menu)
file_menu.add_command(label="New...", command=label1)
file_menu.add_command(label="Exit", command=root.quit)
#Create an edit menu item
edit_menu = Menu(my_menu, tearoff=False)
my_menu.add_cascade(label="Edit", menu=edit_menu)
edit_menu.add_command(label="Save Location", command=save_location)
edit_menu.add_command(label="Copy", command=label1)
def buttonPress():
global press_value
press_value = press_value + 1
if (press_value % 2) == 0:
pressOff()
else:
pressOn()
button_1 = tkinter.Button(text="OFF", width = '10', height = '10', fg = 'red', command = buttonPress)
button_1.pack(side = 'bottom')
If you click 'edit' and then'save location'. It pops up with a box but should show a label about the directory people can choose by picking the browse button. It is not working though, the label is not showing. Thanks for everyone's help in advance.

Related

How to make find and replace system in python

This a simple code in which i have created a text area using tkinter and a menu in which there is a option of find and replace in which if user click on it then a gui will appear in which user will enter a word to whom they want to replace and then a word to whom they want replace with but till now i have just created a gui . But how can i replace word with a word given by user with the text of text area that i have created.
from tkinter import *
import tkinter.font as font
from tkinter import messagebox
root = Tk()
root.title("MyCodeEditor")
editor = Text()
editor.pack()
menu_bar = Menu(root)
def find_replace():
f = Tk()
f.title("Find and Replace")
find_label = Label(f,text = "Find : ")
replace_label = Label(f,text = "Replace : ")
find_label.grid(row = 0 , column = 0)
replace_label.grid(row = 3 , column = 0)
global find_enter
global replace_enter
find_enter = Entry(f,fg = "black" , background = "blue",borderwidth = 5,width = 40)
replace_enter = Entry(f,fg = "black" , background = "blue", borderwidth = 5, width =40 )
find_enter.grid(row = 0 , column = 1)
replace_enter.grid(row = 3 , column = 1)
btn_replace = Button(f,text = 'Replace',fg = 'black',command = None)
btn_replace.grid(row=0, column = 5)
format_bar = Menu(menu_bar , tearoff = 0)
format_bar.add_command(label = 'Find and Replace',command = find_replace)
menu_bar.add_cascade(label = 'Format' ,menu = format_bar )
root.config(menu = menu_bar)
root.mainloop()
Here is a simple example (most of it is just the GUI looks, the main part is the actual replace method):
from tkinter import Tk, Text, Entry, Frame, Button, Toplevel, Label, Menu, TclError, IntVar
normal_font = ('comicsans', 10)
class FindAndReplace(Toplevel):
def __init__(self, parent, text_widget: Text):
Toplevel.__init__(self, parent)
self.focus_force()
self.title('Find and Replace')
self.geometry('500x200')
self.resizable(False, False)
self.parent = parent
self.widget = text_widget
try:
self.start_index = self.widget.index('sel.first')
self.end_index = self.widget.index('sel.last')
except TclError:
self.start_index = '1.0'
self.end_index = 'end'
self.to_find = None
self.to_replace = None
# creating find entry
find_frame = Frame(self)
find_frame.pack(expand=True, fill='both', padx=20)
Label(find_frame, text='Find:', font=normal_font).pack(side='left', fill='both', padx=20)
self.find_entry = Entry(find_frame)
self.find_entry.pack(side='right', expand=True, fill='x')
# creating replace entry
replace_frame = Frame(self)
replace_frame.pack(expand=True, fill='both', padx=20)
Label(replace_frame, text='Replace:', font=normal_font).pack(side='left', fill='both', padx=20)
self.replace_entry = Entry(replace_frame)
self.replace_entry.pack(side='right', expand=True, fill='x')
# creating buttons
button_frame = Frame(self)
button_frame.pack(expand=True, fill='both', padx=20)
Button(button_frame, text='Cancel', font=normal_font,
command=self.destroy).pack(side='right', fill='x', padx=5)
Button(button_frame, text='Replace', font=normal_font,
command=self.replace).pack(side='right', fill='x', padx=5)
def __find_get(self):
self.to_find = self.find_entry.get()
def __replace_get(self):
self.to_replace = self.replace_entry.get()
def replace(self):
self.__find_get()
self.__replace_get()
if not self.to_replace:
return
length = IntVar()
index = self.widget.search(self.to_find, self.start_index, stopindex=self.end_index, count=length)
end_index = self.widget.index(index + f'+{length.get()}c')
self.widget.delete(index, end_index)
self.widget.insert(index, self.to_replace)
root = Tk()
menu_bar = Menu(root)
file_menu = Menu(menu_bar, tearoff=0)
menu_bar.add_cascade(label='File', menu=file_menu)
file_menu.add_command(label='Find and Replace', command=lambda: FindAndReplace(root, text))
root.config(menu=menu_bar)
text = Text(root)
text.pack()
root.mainloop()
Obviously some other functionality could be added such as replace all

Python Tkinter - processing data entered by a user

I want to create a program in Python with Tkinter GUI, and I want it to take string inputs from a user, then I want to do some operations on these strings - in this case, I want to mix parts of two words and get a new word. How can I handle this data entered by a user and use it to receive the result? Below is my code. I couldn't find the answer to this problem and nothing I tried works.
from Tkinter import *
class Window(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
self.master = master
self.init_window()
def init_window(self):
self.master.title("Mix words")
self.pack(fill=BOTH, expand=1)
menu = Menu(self.master)
self.master.config(menu=menu)
entryLbl1 = Label(self, text="Write the first word: ")
entryLbl1.pack()
self.entrytext1 = StringVar()
Entry(self, textvariable=self.entrytext1).pack()
self.buttontext1 = StringVar()
self.buttontext1.set("OK")
Button(self, textvariable=self.buttontext1, command=self.clicked1).pack()
self.label1 = Label(self, text="")
self.label1.pack()
global user_entry1
user_entry1 = self.entrytext1.get()
entryLbl2 = Label(self, text="Write the second word: ")
entryLbl2.pack()
self.entrytext2 = StringVar()
Entry(self, textvariable=self.entrytext2).pack()
self.buttontext2 = StringVar()
self.buttontext2.set("OK")
Button(self, textvariable=self.buttontext2, command=self.clicked2).pack()
self.label2 = Label(self, text="")
self.label2.pack()
global user_entry2
user_entry2 = self.entrytext2.get()
entryLbl3 = Label(self, text="Result: ")
entryLbl3.pack()
self.buttontext3 = StringVar()
self.buttontext3.set("Result")
Button(self, textvariable=self.buttontext1, command=self.clicked3).pack()
self.label3 = Label(self, text="")
self.label3.pack()
def clicked1(self):
input = self.entrytext1.get()
self.label1.configure(text=input)
def clicked2(self):
input = self.entrytext2.get()
self.label2.configure(text=input)
def clicked3(self):
self.user_entry1 = user_entry1
self.user_entry2 = user_entry2
first2a = user_entry1[0:2]
rest_a = user_entry1[2:]
first2b = user_entry2[0:2]
rest_b = user_entry2[2:]
input = first2b + rest_a + " " + first2a + rest_b
self.label3.configure(text=input)
root = Tk()
root.iconbitmap("py.ico")
root.geometry("600x300")
app = Window(root)
root.mainloop()
You need Entry() objects.
The following will show two Entry widgets and a Button.
When the button is pressed, the contents of both of the Entry objects will be printed to the console:
import sys
# Determine if you're running Python 3
is_py_3 = sys.version[0] == '3'
# Import Tkinter for the correct version of Python
if is_py_3:
from tkinter import Button, Entry, Tk
else:
from Tkinter import Button, Entry, Tk
class GUI:
def __init__(self):
# Set up the "Root" or "Parent" of the window.
self.root = Tk()
# Set up two "Entry" widgets.
self.entry1 = Entry(self.root)
self.entry1.insert(0, "Enter something here.")
self.entry2 = Entry(self.root)
self.entry2.insert(0, "and here...")
# Set up a button to handle the event.
self.button = Button(self.root, text="CLICK ME", command=self.onClicked)
self.entry1.pack()
self.entry2.pack()
self.button.pack()
def onClicked(self):
# Print the contents of the entry widgets.
s1 = self.entry1.get()
s2 = self.entry2.get()
print(s1, s2)
app = GUI()
app.root.mainloop()

How to print through local or network printer in tkinter

I want to select one of installed printer on my computer and print through it but my combobox doesn't display the printers on my machine but rather print to my terminal in my IDE .
Have been trying this for days with arriving at the solution to do this.Have installed the win32print module to after reading about it.This my code below:
from tkinter import *
from tkinter import ttk
import win32print
def installed_printer():
printers = win32print.EnumPrinters(2)
for p in printers:
return(p)
def locprinter():
pt = Toplevel()
pt.geometry("250x250")
pt.title("choose printer")
LABEL = Label(pt, text="select Printer").pack()
PRCOMBO = ttk.Combobox(pt, width=35,
textvariable=installed_printer).pack()
BUTTON = ttk.Button(pt, text="refresh",
command=installed_printer).pack()
root = Tk()
root.title("printer selection in tkinter")
root.geometry("400x400")
menubar = Menu(root)
root.config(menu=menubar)
file_menu = Menu(menubar)
menubar.add_cascade(label="File", menu=file_menu)
file_menu.add_command(label="printer", command=locprinter)
LAB = Label(root, text="Comment")
T2 = Text(root, width=40, height=10)
def INFO():
print(T2.get("1.0", END))
Print_Button = Button(root, text ="Print", command =
INFO).place(x=180,y=250)
LAB.pack()
T2.pack()
root.mainloop()
How can i achieve this as i want to print the content in my Text box with tkinter framework.
Is this what you wanted to create?
from tkinter import *
from tkinter import ttk
import win32api
import win32print
import tempfile
def installed_printer():
printers = win32print.EnumPrinters(2)
for p in printers:
return(p)
printerdef = ''
def locprinter():
pt = Toplevel()
pt.geometry("250x250")
pt.title("choose printer")
var1 = StringVar()
LABEL = Label(pt, text="select Printer").pack()
PRCOMBO = ttk.Combobox(pt, width=35,textvariable=var1)
print_list = []
printers = list(win32print.EnumPrinters(2))
for i in printers:
print_list.append(i[2])
print(print_list)
# Put printers in combobox
PRCOMBO['values'] = print_list
PRCOMBO.pack()
def select():
global printerdef
printerdef = PRCOMBO.get()
pt.destroy()
BUTTON = ttk.Button(pt, text="Done",command=select).pack()
root = Tk()
root.title("printer selection in tkinter")
root.geometry("400x400")
menubar = Menu(root)
root.config(menu=menubar)
file_menu = Menu(menubar)
menubar.add_cascade(label="File", menu=file_menu)
file_menu.add_command(label="printer", command=locprinter)
LAB = Label(root, text="Comment")
T2 = Text(root, width=40, height=10, wrap=WORD)
def INFO():
printText = T2.get("1.0", END)
print(printText)
print(printerdef)
filename = tempfile.mktemp(".txt")
open(filename, "w").write(printText)
# Bellow is call to print text from T2 textbox
win32api.ShellExecute(
0,
"printto",
filename,
'"%s"' % win32print.GetDefaultPrinter(),
".",
0
)
Print_Button = Button(root, text ="Print", command=INFO).place(x=180,y=250)
LAB.pack()
T2.pack()
root.mainloop()

Tkinter does not show one frame

I am trying to make a GUI for my program but I have changed my code a lot and I saw that GUI misses one frame but it was fine before.
Could anyone help me and tell why a frame with a button does not appear on the bottom?
Whole "button_part" object does not appear.
from tkinter import *
import tkinter as tk
import os
import glob
BOUNDS = ["Last week", "Last 2 weeks", "Last 3 weeks"]
class settings_part:
path_to_copy = 0
def __init__(self, master, update_func):
path_to_copy = StringVar()
settings_frame = Frame(master, background="")
settings_frame.pack(side=TOP, fill=X)
date_bound = StringVar()
date_bound.set(BOUNDS[1])
date_option = OptionMenu(settings_frame, date_bound, *BOUNDS, command=update_func)
date_option.config(background="#732c30")
date_option.config(foreground="white")
date_option.config(bd=0)
date_option.pack(side=LEFT, padx=5, pady=5)
path_to_copy.set("~/Python/usun")
box_with_path = Entry(settings_frame, textvariable=path_to_copy)
box_with_path.pack(side=RIGHT, padx=5, pady=5)
# s = path_to_copy.get()
class songs_part:
def __init__(self, master, root):
self.songs_frame = Frame(master)
self.update_songs(root.list_of_songs)
self.songs_frame.pack()
def update_songs(self, l):
for song in l:
c = Checkbutton(self.songs_frame, text=song[0], variable=song[1])
c.pack()
class button_part:
def __init__(self, master, copyFunc):
self.button_frame = Frame(master)
btn_image = PhotoImage(file="copybtn.png")
self.copy_button = Button(self.button_frame, command=copyFunc, text="Copy",
image=btn_image, highlightthickness=0, bd=0, activebackground="#732c30")
self.copy_button.pack()
class App:
def __init__(self):
root = Tk()
root.title("Copying songs")
root.geometry("500x500")
root.option_add("*Font", "Calibra")
back_image = PhotoImage(file="back.png")
self.window = Label(root, image=back_image)
self.window.pack(fill="both", expand="yes")
self.list_of_songs = list()
self.make_list_of_songs()
self.set_part = settings_part(self.window, self.update_list)
self.son_part = songs_part(self.window, self)
self.but_part = button_part(self.window, self.copy_songs)
root.mainloop()
def make_list_of_songs(self):
owd = os.getcwd()
os.chdir("/home/stanek/Music/usun")
for file in glob.glob("*.mp3"):
self.list_of_songs.append([file, tk.IntVar()])
os.chdir(owd)
def copy_songs(self):
for s in self.list_of_songs:
print(s)
def update_list(self, arg):
print("updating list with songs from " + arg)
self.son_part = songs_part(self.window, self)
if __name__ == '__main__':
App()
You never pack the button frame.

having trouble in setting up a calendar in tkinter

i have a small ui programm and i need to display a calendar in it or a date picker . (NOTE : userid and password is root")**
i have tried this code :
from Tkinter import *
from PIL import Image, ImageTk
import ttkcalendar
class App():
def __init__(self):
pass
root = Tk()
root.configure(bg='black')
root.attributes('-alpha', 0.0)
def mainWindow(self):
self.root.geometry('{}x{}'.format(600,400))
self.root.attributes('-alpha', 1)
self.root.configure(bg='#404040')
self.ttkcal = ttkcalendar.Calendar(self.root,firstweekday=calendar.SUNDAY)
self.ttkcal.pack()
self.root.wm_title("time sheet management system")
# Create the toolbar as a frame
self.toolbar = Frame(self.root, borderwidth=1, relief='raised')
self.toolbar.configure( bg = '#838383')
# Load all the images first as PNGs and use ImageTk to convert
# them to usable Tkinter images.
self.img1 = Image.open('NewIcon.png')
self.useImg1 = ImageTk.PhotoImage(self.img1)
self.img2 = Image.open('LoadIcon.png')
self.useImg2 = ImageTk.PhotoImage(self.img2)
self.img3 = Image.open('SaveIcon.png')
self.useImg3 = ImageTk.PhotoImage(self.img3)
# Set up all the buttons for use on the toolbars.
newBtn = Button(self.toolbar, image=self.useImg1, command=self.callback)
newBtn.pack(side=LEFT, fill=X)
loadBtn = Button(self.toolbar, image=self.useImg2, command=self.callback)
loadBtn.pack(side=LEFT, fill=X)
saveBtn = Button(self.toolbar, image=self.useImg3, command=self.callback)
saveBtn.pack(side=LEFT, fill=X)
# Add the toolbar
self.toolbar.pack(side=TOP, fill=X)
"""
#create a frame
self.infoArea= Frame(self.root, borderwidth=2,height=40,width=100, relief='raised',bg='red')"""
self.root.mainloop()
"""
# Set up a Text box and scroll bar.
self.scrollbar = Scrollbar(self.root)
self.scrollbar.pack(side=RIGHT, fill=Y)
self.text = Text(self.root)
self.text.pack()
self.text.config(yscrollcommand=self.scrollbar.set)
self.scrollbar.config(command=self.text.yview)"""
def loginClick(self):
self.userid = self.txt1.get()
self.password = self.txt2.get()
print self.userid,self.password
if self.password == 'root' and self.userid == 'root':
self.wi.destroy()
self.mainWindow()
def callback(self):
print "A button was pressed"
def login(self):
self.wi = Toplevel (self.root)
#self.wi.geometry('{}x{}'.format(200,200))
self.wi.configure(bg='#404040')
self.wi.overrideredirect(1)
self.wi.update_idletasks()
self.w = self.wi.winfo_screenwidth()
self.h = self.wi.winfo_screenheight()
self.size = tuple(int(_) for _ in self.wi.geometry().split('+')[0].split('x'))
self.x = self.w/2 - self.size[0]/2
self.y = self.h/2 - self.size[1]/2
self.wi.geometry("%dx%d+%d+%d" % (self.size + (self.x, self.y)))
self.wi.geometry('{}x{}'.format(400,200))
self.frame1 = Frame ( self.wi,bg='#404040' )
self.frame1.pack(side=BOTTOM,fill=X)
self.butt1 = Button(self.frame1,text= "Cancel" , bg = '#838383',fg='white',command = self.wi.destroy)
self.butt1.pack(side=RIGHT,padx=1)
self.butt2 = Button(self.frame1,text= "Login" ,bg = '#838383',fg='white',command = self.loginClick)
self.butt2.pack(side=RIGHT)
"""self.frame2 = Frame ( self.wi,bg='green' )
self.frame2.pack(side=BOTTOM,fill=BOTH)"""
self.lab1 = Label (self.wi,text='UserID',bg='#404040',fg='white')
#self.lab1.pack(side=LEFT,padx=60,pady=20)
self.lab1.place(x=60,y=20)
self.lab2 = Label (self.wi,text='Password',bg='#404040',fg='white')
#self.lab1.pack(side=LEFT,padx=60,pady=20)
self.lab2.place(x=60,y=60)
self.txt1 = Entry( self.wi)
self.txt1.place(x=140,y=20)
self.txt2 = Entry( self.wi,show='*')
self.txt2.place(x=140,y=60)
"""
self.label = Label(self.wi,text="UserID",bg='#838383',fg='white')
self.label.place("""
self.wi.mainloop()
if __name__ == "__main__":
a = App()
#a.root.mainloop()
a.login()
but it is giving error that "name calendar not defined". how can i solve this ?
or is there any other way to implement a calendar or date picker in tkinter.
The code is using calendar module, but it is not importing the module.
self.ttkcal = ttkcalendar.Calendar(self.root, firstweekday=calendar.SUNDAY)
^^^^^^^^^^^^^^^
Simply adding following import statement will solve the problem.
import calendar

Categories