String variable as status in api.update_status with source label [duplicate] - python

This question already has answers here:
Why is my Button's command executed immediately when I create the Button, and not when I click it? [duplicate]
(5 answers)
Closed 3 years ago.
I use Python 2.7.15 and I am trying to create a GUI that will let you tweet with a custom source label ("Twitter for ...") but my current code while accepting the variable for the source label it does not like the status as a variable.
Code:
import tweepy
from Tkinter import *
auth = tweepy.OAuthHandler('lol', 'nice')
auth.set_access_token('try', 'xD')
api = tweepy.API(auth)
def tweet():
message = messageStorage.get()
sourceLabel = sourceLabelStorage.get()
api.update_status(message, source = sourceLabel)
gui = Tk()
gui.title('')
messageStorage = StringVar()
sourceLabelStorage = StringVar()
label0 = Label(gui, text='Enter Tweet').pack()
entry0 = Entry(gui, textvariable=messageStorage).pack()
label1 = Label(gui, text='Enter Source Label').pack()
entry1 = Entry(gui, textvariable=sourceLabelStorage).pack()
button0 = Button(gui, text='Tweet', command=tweet(), bg='#1da1f2').pack(pady=5)
gui.mainloop()
Error:
Traceback (most recent call last):
File "C:/Users/My Name/Desktop/customSourceLabel_twitter.py", line 24, in <module>
button0 = Button(gui, text='Tweet', command=tweet(), bg='#1da1f2').pack(pady=5)
File "C:/Users/My Name/Desktop/customSourceLabel_twitter.py", line 12, in tweet
api.update_status(message, source = sourceLabel)
File "C:\Python27\lib\site-packages\tweepy\api.py", line 195, in update_status
)(post_data=post_data, *args, **kwargs)
File "C:\Python27\lib\site-packages\tweepy\binder.py", line 250, in _call
return method.execute()
File "C:\Python27\lib\site-packages\tweepy\binder.py", line 234, in execute
raise TweepError(error_msg, resp, api_code=api_error_code)
TweepError: [{u'message': u'Missing required parameter: status.', u'code': 170}]
Thanks in advance

From the Tweepy documentation, it looks as if you must explicitly identify that first parameter as status, like so:
api.update_status(status=message, source=sourceLabel)
EDIT: As #Bryan Oakley points out, there is also another bug in your code--in your call to Button(), the parameter command=tweet shouldn't have parentheses after the function name--but that's separate from and in addition to the error message you've posted.

Related

"can only concatenate str (not "int") to str" when zipping list of strings and list of objects

I get this error:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Hunter\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py", line 1883, in __call__
return self.func(*args)
File "c:\Users\Hunter\Documents\Programming\Python Scripts\Scripts\spoolClient\menuScript.py", line 46, in <lambda>
updateJsonButton = Button(preferences, text="Save Preferences", command=lambda: updateJson())
File "c:\Users\Hunter\Documents\Programming\Python Scripts\Scripts\spoolClient\menuScript.py", line 17, in updateJson
for i, j in zip(entryNames, entry):
File "C:\Users\Hunter\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py", line 1643, in cget
return self.tk.call(self._w, 'cget', '-' + key)
TypeError: can only concatenate str (not "int") to str
When trying to run my script:
from tkinter import *
from tkinter.ttk import *
from tkinter import messagebox
from tkinter import filedialog
import qrMaker
import qrReader
import json
settings = {}
#define vars
preferencesSkippedRows = [1, 3, 5, 7, 9, 11]
def openPreferences():
def updateJson():
print("here")
for i, j in zip(entryNames, entry):
print("loopdie")
value = str(j.get())
settings[i]=value
settingsjson = json.dumps(settings)
print(settingsjson)
f = open("preferences.json","w")
f.write(settingsjson)
f.close()
preferences = Tk()
preferences.title("Preferences")
preferences.iconbitmap(qrMaker.getCurrentPath()+'icon.ico')
preferences.geometry('400x600')
topText = Label(preferences, width=30, text="Filament Spool Client Preferences")
cameraText = Label(preferences, width=30, text="Select Camera Instance:")
cameraEntry = Combobox(preferences, width=30, values=qrReader.getCameras())
qrWidthText = Label(preferences, width=30, text="QR Output Width (in.)")
qrWidthEntry = Entry(preferences, width=30)
qrHeightText = Label(preferences, width=30, text="QR Output Height (in.)")
qrHeightEntry = Entry(preferences, width=30)
text = [cameraText, qrWidthText, qrHeightText]
entry = [cameraEntry, qrWidthEntry, qrHeightEntry]
entryNames = ['cameraEntry', 'qrWidthEntry', 'qrHeightEntry']
updateJsonButton = Button(preferences, text="Save Preferences", command=lambda: updateJson())
for i in preferencesSkippedRows:
preferences.grid_rowconfigure(i, minsize=10)
topText.grid(column = 0, row = 0)
row=2
for text, entry in zip(text, entry):
text.grid(column = 0, row = row)
entry.grid(column = 1, row = row)
row+=2
updateJsonButton.grid(column=1, row=row+2)
preferences.mainloop()
openPreferences() #I call script.openPreferences() in my main program but I left this here for debugging purposes
I can see from the error message that the error occurs somewhere in the line that my zip function occurs, but I have no idea what causes this. Oddly enough, this error goes away if instead of setting updateJson equal to the command value of my Tkinter button state, I set updateJson, which calls the function right as the button object is initialized. I also know what the error is saying, I just don't know where an integer is coming from, and how I can fix this issue. Any help would be appreciated.
Update: I've just found that the actual zipping of the two lists is not the problem, but when I introduce the for loop, the same error occurs.
Answering to close out this thread, answer from "user2357112 supports Monica".
The issue in this script is that for text, entry in zip(text, entry) literally uses "entry" in the for loop, and is executed after the button instance is created, meaning that if updateJson is called during the button object initialization, then there will be no error thrown as entry is still defined as a list. However, after for text, entry in zip(text, entry) executes at startup, entry is now defined as the last object in the list entry, no longer the list entry itself. When the user presses the button and updateJson is called, an error is thrown as entry is not a list anymore(I'm not 100% sure on the error part).

Why does python say there are 4 arguments when there are only 3?

I'm writing a Tkinter with gspread app. I believe the connections to the spreadsheets are made properly because i can read data off it. I'm using python 2.7.15 and gspread 0.6.2. I get the error. If i leave out the 'RAW' argument at the end of the function call, I no longer get any errors, but nothing gets written to the spreadsheet.
Exception in Tkinter callback
Traceback (most recent call last):
File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1550, in __call__
return self.func(*args)
File "app.py", line 22, in clicked
sheet.insert_row(insertRow,index,'RAW')
TypeError: insert_row() takes at most 3 arguments (4 given)
import gspread
from oauth2client.service_account import ServiceAccountCredentials
from Tkinter import *
scope = ["https://spreadsheets.google.com/feeds",'https://www.googleapis.com/auth/spreadsheets',"https://www.googleapis.com/auth/drive.file","https://www.googleapis.com/auth/drive"]
creds = ServiceAccountCredentials.from_json_keyfile_name("client_secret.json", scope)
client = gspread.authorize(creds)
sheet = client.open("This").sheet1 # Open the spreadhseet
#data = sheet.get_all_records() # Get a list of all records
#row = sheet.row_values(3) # Get a specific row
#col = sheet.col_values(3) # Get a specific column
#cell = sheet.cell(1,2).value # Get the value of a specific cell
def clicked():
index = sheet.row_count
index+=1
insertRow = [nametxt.get(),placetxt.get(), phonetxt.get()]
sheet.insert_row(insertRow,index,'RAW')
window = Tk()
window.title("Registration application")
window.geometry('700x700')
namelbl = Label(window, text="Name",font=("Ubuntu",20))
placelbl = Label(window, text="Place", font=("Ubuntu",20))
phonelbl = Label(window,text="Phone No", font=("Ubuntu",20))
placetxt = Entry(window,width = 20)
nametxt = Entry(window,width=20)
phonetxt = Entry(window,width = 20)
namelbl.grid(column=1, row=1,)
nametxt.grid(column=2, row=1)
placelbl.grid(column=1, row=2)
placetxt.grid(column=2,row=2)
phonelbl.grid(column =1, row=3)
phonetxt.grid(column = 2,row=3)
button = Button(window, text="submit",command=clicked)
button.grid(column=2, row=5)
window.mainloop()
#sheet.update_cell(2,2, "CHANGED") # Update one cell
You're using an old version of gspread. In the version you're using the definition of insert_row looks like this:
def insert_row(self, values, index=1):
Notice how it takes only three arguments: self (automatically passed when called on an instance), along with values and index. It doesn't accept any other parameters. You need to remove the RAW argument for your code to work with this version of the library.

I can't output my variable as a label in Tkinter

I would like to put a variable in a Tkinter label that prints out the value of the variable 'x'.
I tried to follow the example from the Tkinter documentation but it still seems to give me a trace error 'in second_click lblx2.place(window)'
x = max(numbers)
y = min(numbers)
z = sum(numbers)
a = float(z / len(numbers))
var_x = StringVar()
var_x.set(x)
lblx2 = Label(window, textvariable=var_x, font=('Arial Bold', 15), bg='blue', fg='red')
lblx2.place(window)
I expect it to just place the number on my window like regular text but it does not print anything.
The full error:
Exception in Tkinter callback
Traceback (most recent call last):
File "REDACTED", line 1705, in __call__ return self.func(*args)
File "REDACTED", line 49, in <lambda> btn['command'] = (lambda: second_click())
File "REDACTED", line 102, in second_click lblx2.place(window)
File "REDACTED", line 2188, in place_configure
File "REDACTED", line 1320, in _options cnf = _cnfmerge(cnf)
File "REDACTED", line 104, in _cnfmerge for c in _flatten(cnfs):
TypeError: object of type 'Tk' has no len()
When I remove (window) from place, it stops giving the errors but still does not put the number on the window
I believe the error is that window is not a suitable parameter for a Label object. Instead, it is used to change the location of the element. You could either
turn it into this: lblx2.place(x=whatever,y=whatever) (note: replace whatever with the location)
or
Remove the whole line of code entirely as it's unnecessary
Don't see a problem. Please provide a full example, not just pieces of code one cannot simply run. Here is mine, that DOESN'T reproduce the issue, and it really doesn't get much simpler than this:
from tkinter import *
from random import random
x = random()
root = Tk()
var_x = StringVar()
var_x.set(x)
Label(root, textvariable=var_x).pack()
root.mainloop()

How to pass a entry field value to a function

I am trying to make a GUI based encryption program using tkinter on python3. Here one option is to encrypt an Image now there is an entry field where the user will enter the mode, 1 for RGB and 0 for greyscale. Now I am trying to pass that entry field value to the encrypt and decrypt function which will execute upon pressing the corresponding button. But I am getting an error while I am passing the value to the function. The script where the buttons and the entry field is written, as follows:
global mode
def getvalue():
mode =int(mode_txt.get())
return mode
image_window = Tk()
image_window.geometry ( '350x200' )
image_window.title ('Image Cryptography')
lbl1 = Label(image_window, text = "Select mode(0 for greyscale/ 1 for RGB): " ).place( x=20, y=40 )
mode_txt = IntVar
mode_txt = Entry(image_window, width = 4) #the entry field
mode_txt.place(x= 300, y=40)
mode_txt.bind('<Return>', getvalue)
mode_txt.pack()
Now I am passing the mode like this:
def encrypt():
mode = getvalue()
if(mode == 0): #greyscale
#some code#
The buttons are like this:
btn_decrypt = Button( image_window, text = "Image Decryption", command = decrypt)
btn_decrypt.place( x=20, y=100 )
btn_encrypt = Button( image_window, text = "Image Encryption", command = encrypt)
btn_encrypt.place( x=200, y=100 )
btn_exit = Button( image_window, text = "Go Back" , command = goback).place( x=140, y=150 )
image_window.mainloop()
The error I am getting is:
Exception in Tkinter callback
Traceback (most recent call last):
File "/usr/lib64/python3.7/tkinter/__init__.py", line 1705, in __call__
return self.func(*args)
File "image1.py", line 98, in decrypt
if(mode == 0):
NameError: name 'mode' is not defined
I don't know where I'm am going wrong? Any help will be appreciated. Thank you.

Python timed subprocess.Popen

I have the following code which gets data from a webscrape.
I only just learnt how to use the
subprocess.Popen
and i am trying to ouse my initiative along with other answers to similar questions on how to use the
subprocess.Popen
to execute the script below to get the webscrape data into my insert field updated every 30 seconds or so. But it is not working. Please could you point me in the right direction?
import xlrd
import subprocess
from Tkinter import *
import urllib2
from ttk import *
import Tkinter as tk
class Application(Frame):
"""GUI to display results of 'equity get'"""
def __init__(self, master):
"""initialise the Frame"""
Frame.__init__(self,master)
self.grid()
self.create_widgets()
def create_widgets(self):
"""Create button, text and entry Widget"""
"""what it is i.e. label"""
url = "https://......."
request= urllib2.Request(url)
handle = urllib2.urlopen(request)
content = handle.read()
splitted_page = content.split("<.......">", 1);
splitted_page = splitted_page24[1].split("</.......>", 1)
self.data = Label(self, text ="Data")
self.data1 = Entry(self, width = 10)
self.data1.insert(0,splitted_page[0])
self.data.grid(column = 1, row = 1)
self.data1.grid(column = 2, row = 1)
self.data1.grid(column = 3, row = 1)
a = 0
while a < 10:
a += 1
time.sleep(15)
while True:
out = subprocess.Popen(["C:\Users\.....\Desktop\Py\python.exe","C:\Users\.....\Desktop\..\Python27\.....\tester.py"])
app = Application(root)
root.title("reload test")
root.geometry("700x300")
root.mainloop()
the error i get is
error no 22: invalid syntax referring to the script between the
(["C:\Users\.....\Desktop\Py\python.exe","C:\Users\.....\Desktop\..\Python27\.....\tester.py"])
then multiple command line windows open displaying the same error and i have to shut down the computer to stop it!
i amended the reference to my file with the 'r' prefix as follows:
([r"C:\Users\.....\Desktop\..\Python27\.....\tester.py"])
but removed the python.exe call as it just calling up the command line window. Now, i receive the following error message:
Traceback (most recent call last):
File "C:\Users\....\Desktop\Py\Python27\.....\tester.py", line 46, in <module>
app = Application(root)
File "C:\Users\......\Desktop\Py\Python27\.....\tester.py", line 18, in __init__
self.create_widgets()
File "C:\Users\.....\Desktop\Py\Python27\......\tester.py", line 44, in create_widgets
out = subprocess.Popen([r"C:\Users\Isaac\Desktop\Py\Python27\.....\tester.py"])
File "C:\Users\.....\Desktop\Py\lib\subprocess.py", line 672, in __init__
errread, errwrite)
File "C:\Users\.....\Desktop\Py\lib\subprocess.py", line 882, in _execute_child
startupinfo)
WindowsError: [Error 193] %1 is not a valid Win32 application
Python uses backslash to quote characters, like \n = newline and \t = tab.
Use an r prefix to make a raw string literal, like a Windows file path:
out = subprocess.Popen([r"C:\Users\.....\Desktop\Py\python.exe", r"C:\Users\.....\Desktop\..\Python27\.....\tester.py"])

Categories

Resources