text not properly align in pack. I want the text to be on top and pack on bottom but every time I try to align the "Enter Password Length" disappear
from tkinter import Button, Entry , Label, Tk
from tkinter.constants import END
import pyperclip
import string
password_chars = string.ascii_letters + string.digits + string.punctuation
class gui:
def __init__(self):
self.window = Tk()
self.window.title("Password Generator")
self.window.geometry("300x300")
# Label Frame
label_title = Label(text="Password Generator", fg="#800000",font=("Inter", 15, "bold"))
label_title.pack(pady=15)
self.label = Label(
self.window, text="Enter Password Length",font=("Inter"))
self.label.pack(pady=20,)
# Entry box for number of characters
self.length_entry_box = Entry(self.label, width=24,)
self.length_entry_box.pack(padx=10, pady=15)
if __name__ == '__main__':
gui().window.mainloop()
The problem is you give the master option in the entry as self.label this should be self.window.
master=self.label(or the first parameter) means entry should inside self.label.
from tkinter import Button, Entry, Label, Tk
from tkinter.constants import END
import pyperclip
import string
password_chars = string.ascii_letters + string.digits + string.punctuation
class gui:
def __init__(self):
self.window = Tk()
self.window.title("Password Generator")
self.window.geometry("300x300")
# Label Frame
label_title = Label(text="Password Generator", fg="#800000",font=("Inter", 15, "bold"))
label_title.pack(pady=15)
self.label = Label(
self.window, text="Enter Password Length",font=("Inter"))
self.label.pack(pady=20,)
# Entry box for number of characters
self.length_entry_box = Entry(self.window, width=24,) # self.label changes to self.window.
self.length_entry_box.pack(padx=10, pady=15)
if __name__ == '__main__':
gui().window.mainloop()
In line 23. Removed object self.label,
from tkinter import Button, Entry , Label, Tk
from tkinter.constants import END
import pyperclip
import string
password_chars = string.ascii_letters + string.digits + string.punctuation
class gui:
def __init__(self):
self.window = Tk()
self.window.title("Password Generator")
self.window.geometry("300x300")
# Label Frame
label_title = Label(text="Password Generator", fg="#800000",font=("Inter", 15, "bold"))
label_title.pack(pady=15)
self.label = Label(
self.window, text="Enter Password Length",font=("Inter"))
self.label.pack(pady=20,)
# Entry box for number of characters
self.length_entry_box = Entry(width=24)
self.length_entry_box.pack(padx=10, pady=15)
if __name__ == '__main__':
gui().window.mainloop()
Output:
Related
Hello currently I'm working on a word occurrence counter, I created a gui for it where users can type the words and then press the "count" button and it will count the occurence of each word, however I want to make it so user can instead upload a text file and the word occurrence will count the occurence of each word in the text file instead. Does anyone know how to make the transition? I need to know how to change it from user input words to user upload text files.
import tkinter as tk
from tkinter import *
from collections import Counter
#Functions
def countWords(s):
signos = [',', '.', ';', ':']
cleanstr = ''
for letra in s.lower():
if letra in signos:
cleanstr += ''
else:
cleanstr += letra
strlist = cleanstr.split(' ')
return dict(Counter(strlist))
def button_count():
text = mainWindow.e2.get()
count = countWords(text)
myLabel = Label(root, text=count)
myLabel.pack()
#Graphics
root = tk.Tk()
root.title("Count words")
root.geometry('400x400')
#Background Image Label
bg = PhotoImage(file = "./guibackground.gif")
# Show image using label
label1 = Label( root, image = bg)
label1.place(relx=0.5, rely=0.5, anchor=CENTER)
#Class Window
class Window:
def __init__(self, root):
self.root = root
self.e2 = tk.StringVar()
self.e = tk.Entry(root, textvariable=self.e2, width=35, borderwidth=5)
self.e.pack()
self.button = Button(root, text="Count words", command=button_count)
self.button.pack()
self.exit_button = Button(root, text="Exit", command=root.quit)
self.exit_button.pack()
if __name__ == '__main__':
mainWindow = Window(root)
Use filedialog.askopenfilename method:
import tkinter as tk
from tkinter import filedialog
from collections import Counter
class App(object):
def __init__(self):
self.root = tk.Tk()
self.btn = tk.Button(text='Open File', command=self.open_file)
self.btn.pack()
self.lbl = tk.Label()
self.lbl.pack()
self.root.mainloop()
def open_file(self):
filename = filedialog.askopenfilename(initialdir='/', title='Select file', filetypes=(('text files','*.txt'), ('all files','*.*')))
with open(filename, 'r') as f:
self.lbl.configure(text=f'{Counter(f.read().split())}')
App()
Output:
Below is the main function I use in order to run two files of python but once I click on the buttuon my window freezes.Please tell me a way to perform multi threaading so that I can click both the buttons at once.
import pandas as pd
import numpy as np
from tkinter import *
from tkinter.ttk import *
from tkinter import messagebox
import threading
import Test1
import Test2
# In[ ]:
def Load1():
Test1.func()
messagebox.showinfo( "Successful","Reconcilation Complete")
def Load2():
Test2.func()
try:
messagebox.showinfo( "Successful","Reconcilation Complete")
except Exception as inst:
messagebox.showinfo( "Unsuccessful",inst)
root = Tk()
root.geometry('375x100')
root.title("Reco")
root.configure(background="LightBlue2")
style = Style()
style.configure('TButton', background = 'SeaGreen2', font =
('calibri', 20, 'bold'))
btn1 = Button(root, text = 'Tier Recon', command =threading.Thread(target=Load1).start )
btn1.grid(row = 1, column = 3, pady = 10, padx = 100)
btn2 = Button(root, text = 'View Recon', command =threading.Thread(target=Load2).start)
btn2.grid(row = 2, column = 3, pady = 10, padx = 100)
root.mainloop()
I have assumed your Test1 and Test2 functions are somewhat infinite so I have created this as the format for my Test1.py and Test2.py:
# Test1.py / Test2.py
import tkinter as tk
def func():
while True:
root = tk.Tk()
root.mainloop()
Now with your code I would thoroughly recommend moving away from your current format and moving to Object Oriented Programming as it will save you many headaches in the future!
This here is the code I have written to make it work:
import tkinter as tk
import tkinter.ttk as ttk
import Test1
import Test2
class reco_win:
def __init__(self, master):
self.master = master
self.master.geometry('375x100')
self.master.configure(background="LightBlue2")
style = ttk.Style()
style.configure('TButton', background = 'SeaGreen2', font =
('calibri', 20, 'bold'))
btn1 = ttk.Button(self.master, text = 'Tier Recon', command = lambda: self.master.after(1, self.load1))
btn1.grid(row = 1, column = 3, pady = 10, padx = 100)
btn2 = ttk.Button(self.master, text = 'View Recon', command =lambda: self.master.after(1, self.load1))
btn2.grid(row = 2, column = 3, pady = 10, padx = 100)
def load1(self):
Test1.func()
def load2(self):
Test2.func()
def main():
root = tk.Tk()
reco_win(root)
root.mainloop()
if __name__ == '__main__':
main()
The important bit in this code:
self.master.after(1, self.load1)
What this line of code does is after 1 millisecond it will asynchronously start a new thread and execute the function Test1.func().
This means that you don't have to worry about the issues with managing the multithreading module in python and you can instead work on writing more code!
Hope this helps,
James
P.S.
If you are using a tk.Tk() window in your Test1/Test2.py you could instead use a tk.TopLevel window which would allow you to rewrite this code to read like so:
import tkinter as tk
import tkinter.ttk as ttk
import Test1
import Test2
class reco_win:
def __init__(self, master):
self.master = master
self.master.geometry('375x100')
self.master.configure(background="LightBlue2")
style = ttk.Style()
style.configure('TButton', background = 'SeaGreen2', font =
('calibri', 20, 'bold'))
btn1 = ttk.Button(self.master, text = 'Tier Recon', command = self.load1)
btn1.grid(row = 1, column = 3, pady = 10, padx = 100)
btn2 = ttk.Button(self.master, text = 'View Recon', command =self.load2)
btn2.grid(row = 2, column = 3, pady = 10, padx = 100)
def load1(self):
top = tk.Toplevel()
tk.Label(top, text="Hello").grid(row=0, column=0)
def load2(self):
top2 = tk.Toplevel()
tk.Label(top2, text="Hello 2").grid(row=0, column=0)
def main():
root = tk.Tk()
reco_win(root)
root.mainloop()
if __name__ == '__main__':
main()
I am Creating Multiple tab window using Notebook and in one of tab "Check Box" will created dynamically depending on the values in the Excel . (I am able to read values from Excel and Create the Check Box) . The Number of Check box will be equal to number values in the excel .
In my Excel I have values from 1 to 30 . But i am seeing values till 1 to 11 and other values are down in the UI , But scroll Bar is not active .
Please help me with this .
import tkinter as tk
from dicttoxml import dicttoxml
import xlrd
import GetValueFromExcel
from GetValueFromExcel import ExcelValue
from array import array
from tkinter import *
from tkinter import ttk, Button
from tkinter import *
root = Tk()
CheckBoxSelection=[]
NameOfVariable=[]
KeyName=[]
SelectedCheckbox=[]
dict={}
frame_main = tk.Frame(root)
frame_main.grid(sticky='news')
canvas=tk.Canvas()
class UICreation():
def __init__(self):
print ("I m in __init__")
self.nb=ttk.Notebook(frame_main)
self.page1=ttk.Frame(self.nb)
self.page2=ttk.Frame(self.nb)
def tabcreation(self):
print ("I M in Tab Creation")
self.nb.add(self.page1,text="Select")
canvas = tk.Canvas(self.page1)
canvas.grid(row=0, column=0, sticky="news")
vsb = tk.Scrollbar(self.page1, orient="vertical", command=canvas.yview)
vsb.grid(row=0, column=1, sticky='ns')
canvas.configure(yscrollcommand=vsb.set)
canvas.config(scrollregion=canvas.bbox("all"))
f = tk.Frame(canvas)
canvas.create_window((200, 0), window=f, anchor="n")
self.nb.add(self.page2,text="Add")
self.nb.grid(sticky=N)
print ("I M in checkBox")
ListNumber=len(List_key)
print (ListNumber)
for value in range(0,ListNumber, 1):
NameOfVariable= "checkBox" + str(value)
CheckBoxSelection.append("var"+str(value))
CheckBoxSelection[value]=IntVar()
NameOfVariable = Checkbutton(f, text=str(List_key[value]),variable=CheckBoxSelection[value])
Checkbutton()
NameOfVariable.grid(sticky=NW)
NameOfVariable.cget("text")
KeyName.append(NameOfVariable.cget("text"))
def button(self):
button = Button(frame_main, text="Submit", command=self.OnButtonClick)
button.grid(sticky=NW)
def OnButtonClick(self):
index = 0
SelectedCheckboxValue=[]
for st in (CheckBoxSelection):
if st.get():
SelectedCheckboxKey=KeyName[index]
SelectedCheckboxValue=GetValueFromExcel.row_data_dict[SelectedCheckboxKey]
index+=1
dict={
"Properties": {"id": "ConnectJetSerialNumber"+SelectedCheckboxKey,"value":SelectedCheckboxValue[0],"PrinterName":SelectedCheckboxValue[1],"PrinterName2":SelectedCheckboxValue[2]}
}
print(dict)
xml = dicttoxml(dict, custom_root='test', attr_type=False)
file=open(r"C:\SmallVille\SmallVilleAutoConfigGUI\Selected.xml","a")
file.write(str(xml))
else:
index+=1
if __name__ == '__main__':
ui = UICreation()
ev = GetValueFromExcel.ExcelValue()
t=ev.readExcelValue()
print("I am before print t")
print(t)
print("I am before list")
List_key= list(t.keys())
print (List_key)
ui.tabcreation()
ui.button()
root.mainloop()
UI Screen Shoot also attached
I've created a function btnExit outside the class myWindow and a method inside the class with the same name. I have called each of these in numerous ways and with a number of recommendations to close the current window. Nothing works.
It's obvious from my code that I just learning Python and come from c++.
Two problems:
if I use command=self.btnExit, I get this error: object has no attribute 'btnExit'.
I can call command=btnExit the function is accessed, but nine of the functions I try close the window.
self.btn2 = tk.Button(self, text="EXIT", fg="red", command=btnExit)
Minimally functional code:
#!/usr/bin/python
#Cura json iteration reporter
import os
import sys
from tkinter import *
import tkinter as tk
root = Tk()
root.overrideredirect(1) #disable root window
root.withdraw()
#test data
display = [
" 0 . name = Extruder",
" 1 . version = 2",
" 2 . metadata",
" 3 . . type = extruder",
" 4 . . author = Ultimaker",
" 5 . . manufacturer = Unknown",
" 6 . . setting_version = 1",
" 7 . . visible = False",
" 8 . . position = 0",
" 9 . settings",
" 10 . . machine_settings"
]
line_cnt = 10
pathFilenameExt = "D:/Python/$my Projects/CURA json profiles examples/fdmextruder.def.json"
fileDialogTitle = "Cura profile files"
win_size = '500x500'
# !!!! - this btnExit outside of any class class
def btnExit():
choice = messagebox.askquestion("Exit Program?", "Are you sure?", icon='warning')
if choice == 'yes':
#???what goes here to close current window????
myWindow.destroy()
class myWindow(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
self.parent = parent
display = [] #make sure display list is empty
# !!!! - this btnExit is in the class whose window I want to close
def btnExit(self):
choice = messagebox.askquestion("Exit Program?", "Are you sure?", icon='warning')
if choice == 'yes':
#???what goes here to close current window????
self.parent.deiconify()
self.top.destroy()
#now that we have a dictionary, create a readable formatted list and display it.
# use current filename NOTE: l1_text = StringVar() must be declared at top as global to be changed???
def displysList(self):
self.tk = Tk() #creates a NEW window each time
self.label1 = tk.Label(self, text = pathFilenameExt)
self.label1.pack(side=TOP, anchor=W, fill=X, expand=YES)
self.btn1 = tk.Button(self, text="New File", fg="blue", command=main)
self.btn1.pack(side=TOP, anchor=W, fill=X, expand=YES)
self.btn2 = tk.Button(self, text="EXIT", fg="red", command=btnExit)
self.btn2.pack(side=TOP, anchor=W, fill=X, expand=YES)
self.title('CURA json Lister')
self.resizable(width=True, height=True)
self.geometry(win_size)
#create scroll bar for listbox
self.scrollbary = tk.Scrollbar(self, orient='vertical')
self.scrollbary.pack(side = 'right', fill = 'y' )
self.scrollbarx = tk.Scrollbar(self, orient='horizontal')
self.scrollbarx.pack(side = 'bottom', fill = 'x' )
height =400 #in characters wider and taller than the screen to use all space available
width = 400
#list box create
self.list2Box=tk.Listbox(self, selectmode=EXTENDED)
self.list2Box.config(height=height, width=width)
self.scrollbary.config(command = self.list2Box.yview )
self.scrollbarx.config(command = self.list2Box.xview )
i = 0
while i < line_cnt:
self.list2Box.insert(END,display[i])
i += 1
self.list2Box.pack(side='left')
def main():
#no other setup needed here for now
windA = myWindow #CREATE AN INSTANCE TO CALL ppd
windA.displysList(root) #redisplay each new file
#end main
if __name__ == '__main__':
main()
root.mainloop()
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()