First the code:
main.py
import string
from app import App
group1=[ "spc", "bspc",",","."]#letters, space, backspace(spans mult layers)
# add in letters one at a time
for s in string.ascii_lowercase:
group1.append(s)
group2=[0,1,2,3,4,5,6,7,8,9, "tab ","ent","lAR" ,"rAR" , "uAR", "dAR"]
group3= []
for s in string.punctuation:
group3.append(s)#punc(spans mult layers)
group4=["copy","cut","paste","save","print","cmdW","quit","alf","sWDW"] #kb shortcut
masterGroup=[group1,group2,group3,group4]
myApp =App({"testFKey":[3,2,2,None})
app.py
import tkinter as tk
import static_keys
import dynamic_keys
import key_labels
class App(tk.Frame):
def __init__(inputDict,self, master=None):
tk.Frame.__init__(self, master)
self.grid(sticky=tk.N+tk.S+tk.E+tk.W)
self.createWidgets(self, inputDict)
def createWidgets(self,inDict):
top=self.winfo_toplevel()
top.rowconfigure(0, weight=1)
top.columnconfigure(0, weight=1)
self.rowconfigure(0, weight=1)
self.columnconfigure(0, weight=1)
tempDict = {}
for k,v in inDict.items():
if 1<=v[0]<=3:
tempDict[k] = static_keys(k,*v[1:])
elif v[0] ==4:
tempDict[k] = dynamic_keys(k,*v[1:])
elif v[0]==5:
tempDict[k] = key_labels(k,*v[1:])
for o in tempDict:
tempDict[o].grid()
return tempDict
static_keys.py
import tkinter
class StaticKeys(tkinter.Label):
"""class for all keys that just are initiated then do nothing
there are 3 options
1= modifier (shift etc)
2 = layer
3 = fkey, eject/esc"""
def __init__(t,selector,r,c, parent,self):
if selector == 1:
tkinter.Label.__init__(master=parent, row=r, column=c, text= t, bg ='#676731')
if selector == 2:
tkinter.Label.__init__(master=parent, row=r, column=c, text= t, bg ='#1A6837')
if selector == 3:
tkinter.Label.__init__(master=parent, row=r, column=c, text= t, bg ='#6B6966')
When I run main.py I get:
Traceback (most recent call last):
File "Desktop/kblMaker/main.py", line 13, in <module>
myApp =App({"testFKey":[3,2,2]})
File "/Users/fozbstudios/Desktop/kblMaker/app.py", line 8, in __init__
tk.Frame.__init__(self, master)
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/tkinter/__init__.py", line 2574, in __init__
Widget.__init__(self, master, 'frame', cnf, {}, extra)
File "/Library/Frameworks/Python.framework/Versions/3.3/lib/python3.3/tkinter/__init__.py", line 2067, in __init__
self.widgetName = widgetName
AttributeError: 'dict' object has no attribute 'widgetName'
Why is this? I have a hunch that I need to possibly do more attribute = self.attribute stuff in the inits, but I don't know. That construct confuses me. Also, is the style good? It doesn't seem like i seem many people tasking all their gui construction into one function. If it is poor, please suggest alternatives. Thanks so much for your help!
update1
I followed the advice of #zhangyangyu by changing the order of arguments and got:
Traceback (most recent call last):
File "Desktop/kblMaker/main.py", line 14, in <module>
myApp =App(d)
File "/Users/fozbstudios/Desktop/kblMaker/app.py", line 10, in __init__
self.createWidgets(self, inputDict)
TypeError: createWidgets() takes 2 positional arguments but 3 were given
update2
Traceback (most recent call last):
File "Desktop/kblMaker/main.py", line 14, in <module>
myApp =App(d)
File "/Users/fozbstudios/Desktop/kblMaker/app.py", line 10, in __init__
self.createWidgets(inputDict)
File "/Users/fozbstudios/Desktop/kblMaker/app.py", line 20, in createWidgets
tempDict[k] = StaticKeys(k,*v[1:])
TypeError: __init__() missing 2 required positional arguments: 'parent' and 'self'
update3
now got it down to missing only one arg by adding a parent string in d, changed main.py to reflect. Seems like its wanting me too pass a self, even hough I know i shouldn't
def __init__(inputDict,self, master=None):
This part of your code is wrong. In your code, self is the argument you pass in and inputDict will be the instance of the class. You'd better use:
def __init__(self, inputDict, master=None):
Related
this is my code:
self.msg_entry = Entry(bottom_label, bg="#2C3E50", fg=TEXT_COLOR, font=FONT)
self.msg_entry.place(relwidth=0.74, relheight=0.06, rely=0.008, relx=0.011)
self.msg_entry.focus()
self.msg_entry.bind("<Return>", self._on_enter_pressed)
def _on_enter_pressed(self, event):
msg = self.msg_entry.get()
self._insert_message(msg, "You")
on hovering on on_enter_pressed function, it's showing function is not accessed and I'm getting the following error:
Traceback (most recent call last):
File "GUI.py", line 91, in <module>
app = ChatApplication()
File "GUI.py", line 15, in __init__
self._setup_main_window()
File "GUI.py", line 76, in _setup_main_window
self.msg_entry.bind("<Return>", self._on_enter_pressed)
AttributeError: 'ChatApplication' object has no attribute '_on_enter_pressed'
(I'm using tkinter in python to implement GUI.)
How can I solve this?
You have wrong indentations - _on_enter_pressed has to be outside __init__
def __init__(self):
# ... code ..
self.msg_entry = Entry(bottom_label, bg="#2C3E50", fg=TEXT_COLOR, font=FONT)
self.msg_entry.place(relwidth=0.74, relheight=0.06, rely=0.008, relx=0.011)
self.msg_entry.focus()
self.msg_entry.bind("<Return>", self._on_enter_pressed)
# outside `__init__`
def _on_enter_pressed(self, event):
msg = self.msg_entry.get()
self._insert_message(msg, "You")
from tkinter import *
from glob import glob
import demoCheck
import random
import quitter
from PIL import ImageTk
gifdir = 'd:/Python/Jupyter/Programming Python/Chap 8 - GUI/pic/'
class buttonpics(Frame):
def __init__(self, parent=None, dir='./gifs/', **kwargs):
Frame.__init__(self, parent, **kwargs)
self.pack()
self.lbl = Label(self, text='None', bg='blue', fg='red')
self.lbl.pack(fill=BOTH)
self.btn = Button(self, text='Press me', bg='white', command=self.draw)
self.btn.pack()
self.quitter = quitter.Quitter(self)
self.quitter.pack(anchor=S)
self.files = glob(dir+'*.jpg')
self.images = [(file, ImageTk.PhotoImage(file=file))
for file in self.files]
def draw(self):
name, photo = random.choice(self.images)
self.btn.config(image=photo)
self.lbl.config(text=name)
buttonpics(dir=gifdir).mainloop()
The codes are trying to load jpg formatted pictures to Tkinter through Pillow's ImageTk module. However, the system generated the following error:
> Traceback (most recent call last): File
> "d:/Python/Jupyter/Programming Python/Chap 8 -
> GUI/buttonpics-func.py", line 31, in <module>
> buttonpics(dir=gifdir).mainloop() File "d:/Python/Jupyter/Programming Python/Chap 8 -
> GUI/buttonpics-func.py", line 22, in __init__
> self.images = [(file, ImageTk.PhotoImage(file=file)) File "d:/Python/Jupyter/Programming Python/Chap 8 -
> GUI/buttonpics-func.py", line 22, in <listcomp>
> self.images = [(file, ImageTk.PhotoImage(file=file)) File "C:\ProgramData\Anaconda3\lib\site-packages\PIL\ImageTk.py", line 89,
> in __init__
> image = _get_image_from_kw(kw) File "C:\ProgramData\Anaconda3\lib\site-packages\PIL\ImageTk.py", line 58,
> in _get_image_from_kw
> return Image.open(source) File "C:\ProgramData\Anaconda3\lib\site-packages\PIL\Image.py", line 2930,
> in open
> raise UnidentifiedImageError( PIL.UnidentifiedImageError: cannot identify image file 'd:/Python/Jupyter/Programming Python/Chap 8 -
> GUI/pic\\IMG_4147.jpg' Exception ignored in: <function
> PhotoImage.__del__ at 0x00000226CF6CFD30> Traceback (most recent call
> last): File
> "C:\ProgramData\Anaconda3\lib\site-packages\PIL\ImageTk.py", line 118,
> in __del__
> name = self.__photo.name AttributeError: 'PhotoImage' object has no attribute '_PhotoImage__photo'
If the extension is changed to png, the program can be run smoothly. Does this result from a compatibility issue with jpg format or there are some other reasons? Thank you for the help!
When I was trying to use grid layout, it shows errors when I try to use more widgets but with one widget it shows no errors,I have reviewed the codes many times but i didn't find any solutions,and by the way I'm using python 3.7 and kivy version 2 Here's my code:
import kivy
from kivy.app import App
from kivy.uix.label import Label
from kivy.uix.gridlayout import GridLayout
from kivy.uix.textinput import TextInput
class My_Grid(GridLayout):
def __init__(self, **kwargs):
super(My_Grid, self).__init__(**kwargs)
self.cols = 4
self.rows = 3
self.add_widget(Label(text="First Name: "))
self.FirstName = TextInput(multiline=False)
self.add_widget(self.FirstName)
self.add_widget(Label(text="Last Name: "))
self.LastName = TextInput(mulyiline=False)
self.add_widget(self.LastName)
self.add_widget(Label(text="email: "))
self.Email = TextInput(mulyiline=False)
self.add_widget(self.Email)
class TestApp(App):
def build(self):
return My_Grid()
if __name__ == "__main__":
TestApp().run()
the errors when i use more widgets:
Traceback (most recent call last):
File "C:/Users/Asus/PycharmProjects/untitled3/my.py", line 29, in <module>
TestApp().run()
File "C:\Users\Asus\PycharmProjects\untitled3\venv\lib\site-packages\kivy\app.py", line 829, in run
root = self.build()
File "C:/Users/Asus/PycharmProjects/untitled3/my.py", line 25, in build
return My_Grid()
File "C:/Users/Asus/PycharmProjects/untitled3/my.py", line 18, in __init__
self.LastName = TextInput(mulyiline=False)
File "C:\Users\Asus\PycharmProjects\untitled3\venv\lib\site-packages\kivy\uix\textinput.py", line 527, in __init__
super(TextInput, self).__init__(**kwargs)
File "C:\Users\Asus\PycharmProjects\untitled3\venv\lib\site-packages\kivy\uix\behaviors\focus.py", line 367, in __init__
super(FocusBehavior, self).__init__(**kwargs)
File "C:\Users\Asus\PycharmProjects\untitled3\venv\lib\site-packages\kivy\uix\widget.py", line 350, in __init__
super(Widget, self).__init__(**kwargs)
File "kivy\_event.pyx", line 243, in kivy._event.EventDispatcher.__init__
TypeError: object.__init__() takes exactly one argument (the instance to initialize)
Process finished with exit code 1
At first, you have a mistake in the word 'multiline' in self.LastName and self.Email. Try to fix that.
I want to update my label in python after the loop has started.
Sadly I get the error
File "mygui.py", line 19, in <module>
GUI.user_said("General Kenobi")
File "mygui.py", line 16, in user_said
self.my_label['text'] = self.label_text
File "/usr/local/Cellar/python3/3.6.4_2/Frameworks/Python.framework/Versions/3.6/lib/python3.6/tkinter/__init__.py", line 1486, in __setitem__
self.configure({key: value})
File "/usr/local/Cellar/python3/3.6.4_2/Frameworks/Python.framework/Versions/3.6/lib/python3.6/tkinter/__init__.py", line 1479, in configure
return self._configure('configure', cnf, kw)
File "/usr/local/Cellar/python3/3.6.4_2/Frameworks/Python.framework/Versions/3.6/lib/python3.6/tkinter/__init__.py", line 1470, in _configure
self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
_tkinter.TclError: invalid command name ".!label"
which doesn't help me at all...
My Code:
from tkinter import *
class MyGUI:
"""A simple class"""
def __init__(self):
self.__main_window = Tk()
self.label_text = "Hello There"
self.my_label = Label(self.__main_window, text=self.label_text)
self.my_label.pack()
self.__main_window.mainloop()
def user_said(self, users_request):
"""Returns what the user says"""
self.label_text = "You said:\n{}\n\n".format(users_request)
self.my_label.config(text=self.label_text)
GUI = MyGUI()
GUI.user_said("General Kenobi")
I'm very glad if someone helps me to find a solution for my problem.
Because MyGUI.__init__ calls self.__main_window.mainloop(), it will not return until the main window is destroyed. Therefore, by the time you call GUI.user_said("General Kenobi"), none of the widgets exist any more.
So I try to separate GUI part from logic part, but I can't call logic function from GUI part. Here's the simplified version of the code:
GUI part
import logic
class Program(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.first_list = QListWidget(self)
self.first_list.setGeometry(15, 35, 140, 42)
add_to_list_button = QPushButton('Add', self)
add_to_list_button.setGeometry(165, 35, 30, 20)
add_to_list_button.clicked.connect(lambda: logic.addToList())
self.second_list = QListWidget(self)
self.second_list.setGeometry(205, 35, 140, 192)
for i in range(30):
self.second_list.addItem(logic.list_one[i][3])
And the logic part
import gui
# list_one and list_two go here
def addToList(self):
for i in range(len(gui.Program.second_list)):
if list_one[i][3] == str(gui.Program.second_list.currentItem().text()):
index = i
list_two.append(list_one[index])
When I run the code and press the Add button I get:
Traceback (most recent call last):
File "/************/gui.py", line 30, in <lambda>
add_to_list_button.clicked.connect(lambda: logic.addToList())
TypeError: addToList() missing 1 required positional argument: 'self'
And when I add self and press the button I get:
add_to_list_button.clicked.connect(lambda: logic.addToList(self))
Traceback (most recent call last):
File "**************/gui.py", line 30, in <lambda>
add_to_list_button.clicked.connect(lambda: logic.addToList(self))
File "**************/logic.py", line 23, in addToList
for i in range(len(gui.Program.second_list)):
AttributeError: type object 'Program' has no attribute 'second_list'
Plus I get lots of other errors like "Cannot find reference 'connect' in 'function', etc.". When the whole code is in one file it works fine. But I have no idea how to separate it right. Sorry for lots of code examples.