I'm new to python. I'm trying to set up a GUI with a main window and a modal window to receive the database credentials. The main window has to be in the background when the modal window appears and the user should not interact with it. Actually the application should terminate in case the user fails to provide a valid username and password. I'm presenting part of the code here. What I get is the main window (the modal window does not appear at all) and I can't do anything but shut the program down - not directly; only through visual studio.
'''
import tkinter as tk
class login:
def checkDbCredentials(self, user, password):
if (len(user)<4 or len(password)<4):
return 0
return 1
def ok(self):
us = self.user.get()
pw = self.password.get()
if self.checkDbCredentials(us, pw)==0:
tk.messagebox.showinfo("Error", "Username and Password do not match")
sys.exit(0)
self.dic['user']=us
self.dic['pass']=pw
self.win2.destroy()
def cancel(self, event=None):
self.parent.focus_set()
self.destroy()
def widgets(self):
x = self.win2.winfo_screenwidth()
y = self.win2.winfo_screenheight()
xx = int((x-270)/2)
yy = int((y-85)/2)
geo = "270x85+" + str(xx) + "+" + str(yy)
self.win2.geometry(newGeometry=geo)
self.tempLab= tk.Label(self.win2, text="Username:", pady=5)
self.tempLab1 = tk.Label(self.win2, text="Password:")
self.iuser = tk.Entry(self.win2, textvariable = self.user, width=30)
self.ipass = tk.Entry(self.win2, textvariable = self.password, width=30, show="*")
self.tempLab.grid(column=0, row=0)
self.tempLab1.grid(column=0, row=1)
self.iuser.grid(column=1, row=0)
self.ipass.grid(column=1, row=1)
self.bt = tk.Button(self.win2, text="Submit", command=lambda: self.ok())
self.bt.grid(column=0, row=2, columnspan=2, pady=5)
self.win2.bind("<Return>", self.ok)
self.win2.bind("<Escape>", self.cancel)
def __init__(self, dic, parent):
self.win2 = tk.Toplevel(parent)
self.parent=parent
self.dic = dic
self.user = tk.StringVar()
self.password = tk.StringVar()
self.win2.overrideredirect(1)
self.widgets()
self.win2.transient(parent)
self.win2.grab_set()
self.win2.protocol("WM_DELETE_WINDOW", self.cancel)
self.parent.wait_window(self.win2)
And the main class code is the following:
import tkinter as tk
from tkinter import ttk, X, Y, BOTH
from tkinter import messagebox
import sys
import login
class mainWindow:
def connect(bt, fr):
notImplementedYet()
def notImplementedYet():
msg = tk.messagebox
msg.showinfo("Warning", "Not Implemented yet!")
btX = 20
btY = 5
btSunken = '#aec2c2' # sunken button color
btRaised = '#85adad' # normal button color
rw = 0 # starting row for buttons
cl = 0 # starting column
dbCredentials = {"user":"", "pass":""}
win = tk.Tk()
win.title("Title")
win.geometry(newGeometry="1366x700+00+00")
win.iconbitmap(bitmap="bitmap.ico")
fr1 = tk.Frame(win, width=1366, height=50, background='beige')
fr1.grid(column=cl, row=rw, rowspan=5)
fr2 = tk.Frame(win)
fr2.grid(column=0, row=1)
lb2 = tk.Label(fr2, text="frame 2", background=btRaised)
btConnect = tk.Button(fr1, text="Connect", background = btRaised ,command=lambda: connect(btConnect, fr1), width=btX, height=btY)
btConnect.grid(column=0, row=0)
log = login.login(dbCredentials, win)
win.wait_window(log.win2)
print(dbCredentials)
win.mainloop()
win = mainWindow()
The question is why is the modal window not appearing? I've tried placing the 'wait_window' in the other class as well but it's still not working.
Related
from tkinter import *
def first():
root1 = Tk()
Button(root1, text = 'get Second', command= second).pack()
root1.mainloop()
def second():
root2 = Tk()
user_input = StringVar()
Entry(root2, text = user_input).pack()
Button(root2, text = 'submit', command = lambda : print(user_input.get(), '\t printed')).pack()
root2.mainloop()
first()
You are making a few basic mistakes in here -
You if want to use a second window, it should be Toplevel not root Tk window. There should be only one root window in the program. This should act as parent to all the windows.
Its a good practice in most of the cases to define the widgets like Button, Entry separately and then pack() them.
Entry should have 'textvariable' not 'text'
Following is the updated code which may help you -
from tkinter import *
root = Tk()
def first():
button = Button(root, text = 'get Second', command= second)
button.pack()
root.mainloop()
def second():
window2 = Toplevel(root)
user_input = StringVar()
entry = Entry(window2, textvariable=user_input)
entry.pack()
button = Button(window2, text = 'submit', command = lambda: print(user_input.get()))
button.pack()
first()
I'm trying to make a program that has a button that will open a picture if a variable is in a certain state, and change how the button looks (or maybe show a different picture) if it's not. I have been trying to work through the bugs I've been getting.
This is honestly intermediary code so I can understand how to make what I'm actually trying to do, make a network-enabled GUI for some physical buttons.
I've tried passing blueButton in as a variable, but that didn't work.
import tkinter as tk
weather = "sunny"
class Application(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.master = master
self.pack()
self.create_widgets()
def create_widgets(self):
self.blueButton = tk.Button(self, fg = "blue")
self.blueButton["text"] = "I'm Blue"
self.blueButton["command"] = self.change
self.blueButton.pack(anchor="nw")
self.quit = tk.Button(self, text = "QUIT", fg = "red",
command = self.master.destroy)
self.quit.pack(side="bottom")
self.pack(fill = "both", expand = 1)
def change(self):
global weather
if weather == "sunny":
w = tk.Canvas(root, width=400, height=750)
img = tk.PhotoImage(file = "haunter.gif")
w.create_image((200, 200), image = img)
w.pack()
else:
self.blueButton["bitmap"] = "error"
root = tk.Tk()
root.geometry("400x300")
app = Application(master = root)
app.mainloop()
The canvas gets made, but the picture doesn't show up, the "quit" button just moves.
I've also gotten the error "name blueButton is not defined".
You could keep the image as an attribute of your App, put it on a canvas, then show or hide the canvas depending on the weather.
import random
import tkinter as tk
class Application(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.master = master
self.pack()
self.create_widgets()
def create_widgets(self):
self.blueButton = tk.Button(self, fg = "blue")
self.blueButton["text"] = "I'm Blue"
self.blueButton["command"] = self.change
self.blueButton.pack()
self.quit = tk.Button(self, text = "QUIT", fg = "red",
command = self.master.destroy)
self.quit.pack()
self.pack(fill = "both", expand = 1)
self.canvas = tk.Canvas(root, width=400, height=750)
# self.sunny_img = tk.PhotoImage(file="haunter.gif")
self.sunny_img = tk.PhotoImage(file="rapporteur.gif")
self.canvas.create_image((200, 200), image=self.sunny_img)
def change(self):
weather = ['sunny', 'rainy']
current_weather = random.choice(weather)
if current_weather == 'sunny':
self.canvas.pack()
self.blueButton["bitmap"] = ''
else:
self.canvas.pack_forget()
self.blueButton["bitmap"] = "error"
root = tk.Tk()
root.geometry("400x300")
app = Application(master = root)
app.mainloop()
im new to Python3.6.2
So I want a program that takes an input (Via text box from tkinter) and outputs a word in my custom "language"
with this function
def Mescre(n):
Words = (n)
Mes = str.maketrans('abcdefghijklmnopqrstuvwxyz', 'ektnopzcamjqwyuxsbfdiglhrv')
print(Words.translate(Mes))
and here's what i want the window to look like
from tkinter import*
root = Tk()
Mescre = Label(root, text="Input:")
English = Label(root , text="Output:")
label1.grid(row=0, sticky=E)
label2.grid(row=1, sticky=E)
entry1 = Entry(root)
entry2 = Entry(root)
entry1.grid = (row=0, column=1)
entry2.grid = (row=1, column=1)
root.mainloop()
if "hello" was in the Input text box, i want the output to be "coqqu" in the Output text box.
See my example below:
from tkinter import *
class App:
def __init__(self, root):
self.root = root
self.sv = StringVar()
self.Mes = str.maketrans('abcdefghijklmnopqrstuvwxyz', 'ektnopzcamjqwyuxsbfdiglhrv')
self.entry = Entry(self.root, textvariable = self.sv)
self.label = Label(self.root)
self.entry.pack()
self.label.pack()
self.sv.trace("w", self.callback)
def callback(self, *args):
self.label.configure({"text": self.entry.get().translate(self.Mes)})
root = Tk()
App(root)
root.mainloop()
Here we define a StringVar() to be the value of the attribute textvariable for the Entry widget.
We then assign a callback to a trace() on the variable so that whenever the variable is updated (When someone types in the Entry) we call callback().
Within callback() we use configure() on the Label widget in order to set the text to equal the post translation version of the value of the Entry widget.
This creates a "live updating" translation effect.
Here's a basic example:
import tkinter as tk
root = tk.Tk()
def Mescre():
val = textfield.get()
Words = (val)
Mes = str.maketrans('abcdefghijklmnopqrstuvwxyz', 'ektnopzcamjqwyuxsbfdiglhrv')
print(Words.translate(Mes))
textfield = tk.Entry(root)
textfield.pack()
button = tk.Button(root, command=Mescre, text='Push')
button.pack()
root.mainloop()
Updated:
import tkinter as tk
root = tk.Tk()
def Mescre():
val = textfield.get()
Words = (val)
Mes = str.maketrans('abcdefghijklmnopqrstuvwxyz', 'ektnopzcamjqwyuxsbfdiglhrv')
translation = Words.translate(Mes)
#print(translation)
outputfield.delete(0, tk.END)
outputfield.insert(0, translation)
textfield = tk.Entry(root)
textfield.pack()
outputfield = tk.Entry(root)
outputfield.pack()
button = tk.Button(root, command=Mescre, text='Push')
button.pack()
root.mainloop()
The code picture needs to fit the screen size perfectly. I saw a bunch of tutorials but nothing seems to work.I tried adding a canvas but it covers half the screen.All my buttons go under the image itself not over it. It's getting on my nerves .
here's my code :
import tkinter as tk
import PIL
from PIL import Image, ImageTk
from tkinter import *
from tkinter import filedialog
from tkinter import messagebox
root = Tk()
w = Label(root, text="Send and receive files easily")
w.config(font=('times', 32))
w.pack()
def create_window():
window = tk.Toplevel(root)
window.geometry("400x400")
tower= PhotoImage(file="D:/icons/tower.png")
towlab=Button(root,image=tower, command=create_window)
towlab.pack()
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("Bifrost v1.0")
self.pack(fill=BOTH, expand=1)
self.img1 = PhotoImage(file="D:/icons/download.png")
self.img2 = PhotoImage(file="D:/icons/upload.png")
sendButton = Button(self, image=self.img2)
sendButton.place(x=305, y=15)
receiveButton = Button(self, image=self.img1)
receiveButton.place(x=355, y=15)
menu = Menu(self.master)
self.master.config(menu=menu)
file = Menu(menu)
file.add_command(label='Exit', command=self.client_exit)
menu.add_cascade(label='File', menu=file)
edit = Menu(menu)
edit.add_command(label='abcd')
menu.add_cascade(label='Edit', menu=edit)
help = Menu(menu)
help.add_command(label='About Us', command=self.about)
menu.add_cascade(label='Help', menu=help)
def callback():
path = filedialog.askopenfilename()
e.delete(0, END) # Remove current text in entry
e.insert(0, path) # Insert the 'path'
# print path
w = Label(root, text="File Path:")
e = Entry(root, text="")
b = Button(root, text="Browse", fg="#a1dbcd", bg="black", command=callback)
w.pack(side=TOP)
e.pack(side=TOP)
b.pack(side=TOP)
def client_exit(self):
exit()
def about(self):
top = Toplevel()
msg = Message(top, text="This is a project developed by Aditi,Sagar and
Suyash as the final year project.",
font=('', '15'))
msg.pack()
top.geometry('200x200')
button = Button(top, text="Okay", command=top.destroy)
button.pack()
top.mainloop()
root.resizable(0,0)
#size of the window
root.geometry("700x400")
app = Window(root)
root.mainloop()
Overlaying elements is tricky. I think this might be approximately what you're looking for. At least it's a start...
import PIL
from PIL import Image, ImageTk
from tkinter import *
from tkinter import filedialog
from tkinter import messagebox
root = Tk()
class Window:
def __init__(self, master=None):
tower = PIL.Image.open("Images/island.png")
master.update()
win_width = int(master.winfo_width())
win_height = int(master.winfo_height())
# Resize the image to the constraints of the root window.
tower = tower.resize((win_width, win_height))
tower_tk = ImageTk.PhotoImage(tower)
# Create a label to hold the background image.
canvas = Canvas(master, width=win_width, height=win_height)
canvas.place(x=0, y=0, anchor='nw')
canvas.create_image(0, 0, image=tower_tk, anchor='nw')
canvas.image = tower_tk
frame = Frame(master)
frame.place(x=win_width, y=win_height, anchor='se')
master.update()
w = Label(master, text="Send and receive files easily", anchor='w')
w.config(font=('times', 32))
w.place(x=0, y=0, anchor='nw')
master.title("Bifrost v1.0")
self.img1 = PhotoImage(file="Images/logo.png")
self.img2 = PhotoImage(file="Images/magnifier.png")
frame.grid_columnconfigure(0, weight=1)
sendButton = Button(frame, image=self.img2)
sendButton.grid(row=0, column=1)
sendButton.image = self.img2
receiveButton = Button(frame, image=self.img1)
receiveButton.grid(row=0, column=2)
receiveButton.image = self.img1
menu = Menu(master)
master.config(menu=menu)
file = Menu(menu)
file.add_command(label='Exit', command=self.client_exit)
menu.add_cascade(label='File', menu=file)
edit = Menu(menu)
edit.add_command(label='abcd')
menu.add_cascade(label='Edit', menu=edit)
help = Menu(menu)
help.add_command(label='About Us', command=self.about)
menu.add_cascade(label='Help', menu=help)
def callback():
path = filedialog.askopenfilename()
e.delete(0, END) # Remove current text in entry
e.insert(0, path) # Insert the 'path'
# print path
w = Label(root, text="File Path:")
e = Entry(root, text="")
b = Button(root, text="Browse", fg="#a1dbcd", bg="black", command=callback)
w.pack(side=TOP)
e.pack(side=TOP)
b.pack(side=TOP)
def client_exit(self):
exit()
def about(self):
message = "This is a project developed by Aditi,Sagar and"
message += "Suyash as the final year project."
messagebox.showinfo("Delete Theme", message)
root.resizable(0,0)
#size of the window
root.geometry("700x400")
app = Window(root)
root.mainloop()
I am trying to migrate the code below (which is in tkinter) to pyqt. I am very new to pyqt. I could not get much details.
import os, sys, time
import os.path
import shutil
import sys
import Tkinter as tk
from Tkinter import *
root = Tk()
frame = Frame(root)
def enable_():
# Global variables
if (var.get()==1):
E5.config(state=NORMAL)
E5.insert(0, 1)
for c in checkbuttons:
c.config(state=NORMAL)
# disable test selection
else:
E5.delete(0, END)
E5.config(state=DISABLED)
for c in checkbuttons:
c.config(state=DISABLED)
# Select geometry
root.geometry("500x570+500+300")
root.title('Test Configure')
# Global variable declaration
global row_me
global col_me
row_me =9
col_me =0
L1 = Label ().grid(row=0,column=1)
Label (text='Target IP Address').grid(row=1,column=0)
E4 = Entry(root, width=20)
E4.grid(row=1,column=1)
L1 = Label ().grid(row=2,column=1)
variable = StringVar()
# Check button creation
var = IntVar()
var_mail = IntVar()
# Create check buttons
R1=Checkbutton(root, text = "Enable Test Suite Selection", variable = var, \
onvalue = 1, offvalue = 0, height=1, \
width = 20, command=enable_)
R1.grid(row=3,column=1)
R2=Checkbutton(root, text = "Send Email", variable = var_mail, \
onvalue = 1, offvalue = 0, height=1, \
width = 20)
R2.grid(row=3,column=2)
L5 = Label (text='Number of Loop').grid(row=4,column=0)
E5 = Entry(root, width=5)
E5.grid(row=4,column=1)
E5.config(state=DISABLED)
L2 = Label ().grid(row=21,column=1)
# List of Tests
bottomframe = Frame(root)
bottomframe.grid(row=24,column=1)
# Reset Button
configbutton = Button(bottomframe, text="Reset", fg="black")
configbutton.grid(row=24,column=2,padx=5, pady=0)
# Quit Button
configbutton = Button(bottomframe, text="Quit", fg="red")
configbutton.grid(row=24,column=3)
# Submit Button
blackbutton = Button(bottomframe, text="Submit", fg="black")
blackbutton.grid(row=24,column=4,padx=5, pady=0)
#Check buttons for test suite selection
test_suite_name=[name for name in os.listdir(".") if (os.path.isdir(name) and name.startswith('test-') )]
L34 = Label (text='Select Test Suite To Be Executed').grid(row=7,column=1)
L11 = Label ().grid(row=9,column=1)
row_me =9
col_me =0
checkbuttons = [create_checkbutton(name) for name in test_suite_name ]
for c in checkbuttons:
c.config(state=DISABLED)
# initiate the loop
root.mainloop()
I have written this code but I am not sure how to make the grid and location for each widget in pyqt:
import sys
from PyQt4 import QtGui
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
SubmitButton = QtGui.QPushButton("OK")
CancelButton = QtGui.QPushButton("Cancel")
ResetButton = QtGui.QPushButton("Reset")
edit1 = QLineEdit()
edit2 = QLineEdit()
cb = QtGui.QCheckBox('Enable Test suite selection', self)
cb.move(150, 100)
#cb.stateChanged.connect(self.changeTitle)
cb2 = QtGui.QCheckBox('Send mail', self)
cb2.move(300, 100)
# cb2.stateChanged.connect(self.changeTitle)
hbox = QtGui.QHBoxLayout()
hbox.addStretch(1)
hbox.addWidget(SubmitButton)
hbox.addWidget(CancelButton)
hbox.addWidget(ResetButton)
hbox.addWidget(edit1)
hbox.addWidget(edit2)
hbox.addWidget(cb)
hbox.addWidget(cb2)
vbox = QtGui.QVBoxLayout()
vbox.addStretch(1)
vbox.addLayout(hbox)
self.setLayout(vbox)
self.setGeometry(100, 100, 500, 650)
self.setWindowTitle('HMI')
self.show()
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
Thank you!
You can either do the designing part in your code or through a QT Designer which ships with PyQt4. and some examples can be found in the path C:\Python26\Lib\site-packages\PyQt4\examples and documentation in the path C:\Python26\Lib\site-packages\PyQt4\doc\html\modules.html if you are using windows. Hope this helps.